DSP: Power of Two Approximation

Post your Gambas programming questions here.
Post Reply
User avatar
Cedron
Posts: 156
Joined: Thursday 21st February 2019 5:02pm
Location: The Mitten State
Contact:

DSP: Power of Two Approximation

Post by Cedron »

This is in support of my answer here:

https://www.dsprelated.com/thread/8959/ ... nentiation

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

' Gambas module file

Private Lookup_V As New Float[]
Private Lookup_L As New Float[]
Private Ln2 As Float

'========================================================================
Public Sub Main()

        Dim v, ev As Float

        v = 1 / 32
        
        Do 
            ev = Exp(v)
            Lookup_V.Add(v)
            Lookup_L.Add(ev)
            Print v, ev
            v += 1 / 16
        Loop Until ev > 2.0
        
        Ln2 = Log(2)
        
        Print 2 ^ (0.5), Sqr(2.0), TwoToPower(0.5)

End
'========================================================================
Sub TwoToPower(x As Float) As Float

        Dim n, bbbb As Integer, f, v, y, ey As Float

        n = Int(x)
        f = x - n
        v = Ln2 * f
        bbbb = Int(16 * v)
        y = v - Lookup_V[bbbb]

        ey = 1 + y * (1 + y * (1 / 2 + y / 6))
        
        Print y, Exp(y), ey
        
        Return 2 ^ n * Lookup_L[bbbb] * ey

End
'========================================================================
Here is the output:

Code: Select all

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!
Post Reply