DSP: Power of Two Approximation

Post

Posted
Rating:
#1 (In Topic #288)
Avatar
Regular
Cedron is in the usergroup ‘Regular’
This is in support of my answer here:  

Fixed point exponentiation

The following program shows how to calculate an approximation of two raised to a float value.  The argument is assumed to be positive.


Code (gambas)

  1. ' Gambas module file
  2.  
  3. Private Lookup_V As New Float[]
  4. Private Lookup_L As New Float[]
  5.  
  6. '========================================================================
  7. Public Sub Main()
  8.  
  9.         Dim v, ev As Float
  10.  
  11.         v = 1 / 32
  12.        
  13.         Do
  14.             ev = Exp(v)
  15.             Lookup_V.Add(v)
  16.             Lookup_L.Add(ev)
  17.             Print v, ev
  18.             v += 1 / 16
  19.         Loop Until ev > 2.0
  20.        
  21.         Ln2 = Log(2)
  22.        
  23.         Print 2 ^ (0.5), Sqr(2.0), TwoToPower(0.5)
  24.  
  25. '========================================================================
  26. Sub TwoToPower(x As Float) As Float
  27.  
  28.         Dim n, bbbb As Integer, f, v, y, ey As Float
  29.  
  30.         n = Int(x)
  31.         f = x - n
  32.         v = Ln2 * f
  33.         bbbb = Int(16 * v)
  34.         y = v - Lookup_V[bbbb]
  35.  
  36.         ey = 1 + y * (1 + y * (1 / 2 + y / 6))
  37.        
  38.         Print y, Exp(y), ey
  39.        
  40.         Return 2 ^ n * Lookup_L[bbbb] * ey
  41.  
  42. '========================================================================
  43.  

Here is the output:

Code

0.03125 1.0317434074991
0.09375 1.09828514030783
0.15625 1.1691184461695
0.21875 1.2445201077661
0.28125 1.32478475872887
0.34375 1.41022603492571
0.40625 1.50117780000012
0.46875 1.59799544995063
0.53125 1.7010573018484
0.59375 1.81076607211939
0.65625 1.92755045016754
0.71875 2.05186677348798
0.002823590279973       1.00282758036558        1.00282758036293
1.4142135623731 1.4142135623731 1.41421356236936

.... and carry a big stick!
Online now: No Back to the top
1 guest and 0 members have just viewed this.