• Welcome to the new Internet Infidels Discussion Board, formerly Talk Freethought.

Python

Calculating e^x


Scroll down to Representations in the link.

e^x = lim n-> inf (1 + x/n)^n
x = 1 you get e
x = 0 you get 1 ...laws of exponents are satisfied

x = 2
n = 100000000
ex = math.pow(math.e,x) # calculate e^x using Python built in
ep = pow(1. + x/ne,n) # calculate E^x using a method from the link


Result comparing both calculation, a small difference.
7.3890560989306495 7.389056025405986 7.352466369070498e-08

I have no idea what solution Python uses, but it is not using tables.

You really do not know this?

This is not genius level, it is common knowledge in math and engineering.

When I got my first computer in the 80s I went through the books coding in C things like series expansions for math functions. More for understanding than usage. I have always been curious and inquisitive.

Common methods for calculating trig and log functions are on the net. Code in Python and compare to your coding. I would not deprive you of a valuable learning experience.

Python is open sourced, you can find the code that does logs.


The code I posted for the inverse error function is a series.
 
NumPy - Numerical Python

Its basic unit of data is the array, and that data structure can have an arbitrary number of dimensions, much like in Matlab and Octave and Mathematica and Maple.

That data structure can contain signed integers, unsigned integers, floating-point numbers, and floating-point complex numbers, all with various sizes, and also data structures, C pointers, and Python objects.

Once one creates an array, one can access and update individual elements and array slices in it, and one can apply a variety of functions to it. One can also do Fourier transforms and several linear-algebra operations: matrix multiplication, solution of systems of linear equations, matrix inversion, singular value decomposition, and eigensystems. SVD is useful for ill-conditioned problems, and eigensystems for finite-element oscillation problems and principal components analysis, a common form of data analysis.

SciPy - Scientific Python
  • Numerous special functions: statistical distributions, Bessel functions, elliptic functions, orthogonal polynomials, ...
  • Sparse arrays: lists of (row position, column position, value)
  • More linear-algebra operations and special matrices
  • Interpolation and data smoothing
  • More Fourier transforms: discrete cosine and sine transforms
  • Function optimization
  • Numerical integration and solution of ordinary differential equations
  • Signal processing: B-splines, filtering, spectral analysis, detrending (removal of data trends)
 
lpetrich, anyone who even remotely familiar with python knows that it has packages for virtually everything.
 
Here you go.

After a short review o whats on the net, a log function. Not optimum but it works.

Go over to the programming thread if you want to discuss it in C.

Code:
def log(x):
    if x == 1:  return 0
    if x <= 0 : return ma.nan
    lnx = 0
    n1 = 100
    n2 = int(1e8)

    if x < 1:
        for k in range(1,n1):
            lnx += pow(-1,k+1)*pow(x-1,k)/k
        return lnx
    
    dy = (x-1.)/(n2-1)
    y = 1.
    for i in range(n2):
        lnx += dy/y
        y += dy
    print(y)
    return lnx     
    
x = 123
lnp = ma.log(x)
lnc= log(x)
print(lnp,"   ",lnc,"   ",lnp-lnc)
 
Python is open sourced, you can find the code that does logs.
All the more reasons for you go and find the code which supports your claims.
Anyone who clams that binary computer math and base 10 paper and pencil math are not equivalent, and who claims logarithms can not be calculated on a computer has no credibility...despite what you conjure up from the net.

The obvious question is what math do you use to create a table of logarithms? Which I knew you could not answer.
 
Anyone who clams that binary computer math and base 10 paper and pencil math are not equivalent, and who claims logarithms can not be calculated on a computer has no credibility
Anyone who constantly lies and bullshits instead of admitting being wrong has no credibility.
 
It took you a while to find the Taylor expansion.

More hand waving.

You claim logarithms can not be computed on a computer, that tables are needed. Maybe that is so in Siberia. You claimed there is no equivalence between binary and base 10 math, I showed that they are equivalent. Common knowledge, but maybe not in Siberia.

I demonstrated how can can be calculated.

All else is evasion on your part.

Again, how would you generate a table of logarithms? Post the math, perhaps a Taylor approximation. What specifically do you mean by 'not in the way I think'.

If you do not begin to answer with detailed math than I will assume you are bluffing.
 
It took you a while to find the Taylor expansion.
Yet, you are still searching for it
It did not. In fact I can calculate log without even being aware of taylor expansion existence.
You claim logarithms can not be computed on a computer, that tables are needed.
That's a lie.
I said library functions do not use taylor expansions for the bulk of the argument.
In fact it does not even have to use it for very small argument, but it makes sense for very small argument so they do.

Yes, tables are used for all functions. That's just a fact which I have known since forever.
And yes, multiplication, division, addition/subtraction also use tables.
Tables are used because they are faster, in some cases way way faster and more accurate (for library functions) too.

You don't know shit. You are an old man who decided to learn python. That's cool and commendable.
But don't assume that learning basics of python makes you smartest men on this forum.
I am definitely smarter and way more educated than you are.
 
Last edited:
Here you go.

After a short review o whats on the net, a log function. Not optimum but it works.

Go over to the programming thread if you want to discuss it in C.

Code:
def log(x):
    if x == 1:  return 0
    if x <= 0 : return ma.nan
    lnx = 0
    n1 = 100
    n2 = int(1e8)

    if x < 1:
        for k in range(1,n1):
            lnx += pow(-1,k+1)*pow(x-1,k)/k
        return lnx
 
    dy = (x-1.)/(n2-1)
    y = 1.
    for i in range(n2):
        lnx += dy/y
        y += dy
    print(y)
    return lnx
 
x = 123
lnp = ma.log(x)
lnc= log(x)
print(lnp,"   ",lnc,"   ",lnp-lnc)
Genius, try x=0.00001
And measure how much time your stupid code takes.
My code for exp(x) takes 3 multiplications. This stupid snippet you wrote has a 100 million iterations.
Yes, I sometimes replace library functions with my own. It makes sense when range of the argument is relatively limited and you don't need absolute, last bit accuracy. And yes, normal code more less guarantees last bit accuracy, whereas your stupid taylor expansion does not and in fact has no accuracy at all for x=0.00001. It produces incorrect result.
and even for your x=123 it has only 1.e-7 precision when it should have about 1e-15 to be considered correct.
Your code is utter garbage.
You searched the internet for formulas and put them into code without thinking.
 
Last edited:
You said tables were required to do multiplication with logarithms which was easily demons ted in Python.

You also said tablea re required before the operations I posted.

It means you can't use your method in computers, that is if your goal to somehow implement multiplication operation through logarithm.


And strictly speaking all operation use tables in practice, multiplication-division, even addition-subtraction.


Not really. You are just trying to cover your mistakes. Computers do not use tables per se as you infer to look something up. Computers use definitions of arithmetic orations, in binary not base 10.

As I showed base 2 and base 10 multilcation are both shift and add on paper in in a computer. You called that nonsense.

Back in the day with early C compilers I did have to write my own functions at times when C math library functions did not work properly. Borland.

So how woud you calculate the natural log? As this is a software thread in code.
 
So how woud you calculate the natural log? As this is a software thread in code.
I posted the easiest variant of the code for log(x).
Unlike your garbage it produces results which pretty much coincides with library function everywhere. Plus it is fast.
I don't see comments from you, why is that?
 
So how woud you calculate the natural log? As this is a software thread in code.
log(x), is an inverse function of exp(x). Inverse functions can be very efficiently calculated using Newtonian method.
Newtonian method has quadratic convergence.
exp(x) only requires calculation of exp(x) for x=1 which is constant e. Actually it does not have to be x=1 it can be any number. does not really matter. After that, one can use sqrt() to calculate fractions exp(1/2), exp(1/4), exp(1/8)........
and multiples exp(2), exp(4), exp(8).
That way one builds a table which can be used to calculate exponent of any number by simply multiplying numbers from the table.

And exp(1) is calculated using taylor expansion. In reality of course it is better to start with smaller x=1/2^n for some larger n.

Of course log(x) can be calculated directly using the same techniques as for exp. All you need is to calculate logarithm of some number and then build the table using sqrt.

This is how values in the tables can be calculated. Of course I would simply use a known value of number e.

Now, here is homework for you: Using what I just told you write simple and efficient code for calculating f(x)=1/x using addition/subtraction and multiplication (I have already asked you to do that few times)
 
Last edited:

Moving up on my Python learning curve, Inverse Fourier Transform.

Coupled with a graphics package like Gnuplot Python is a good math tool with some reservations.

Python is not typed. Python speak uses the terms mutable and immutable.

Print a = 'Hello" followed by a = 1.23 and the interpreter sees no difference.

You can type an array x = array.array("i',10[0]) creating an int array. If I try x[1] = 1.23 assigning a float to an int array an error will be generated. That helps with preventing math problems, but if I follow by x = 'Hello' the array is gone.

The inverse transform uses complex arrays, it took me a while to figure out how to pass complex arrays between functions. One way was to use two double arrays, one for for real andone for imaginary parts.

There is no complex type for a typed array. But a list of complex numbers can be created x = 10*[complex(0,0)].

A list mixes types in any part of the array. It makes sense when dealing with complicated data bases with mixed data types.


The inverse transform takes a complex frequency spectrum and constructs the corresponding time domain signal. A practical usage can be taking the forward transform of a signal with a frequency component you do not want , zeroing out the offending frequency in the complex array, and taking the inverse transform.

A pulse or a signal of the sum of two sines can be created.

plot.plt is a Gnuplot script that plots the signal, the reconstructed signal, and the frequency spectrum.

Comment out make_sin() or make_pulse() to see the inverse transform.

You can play around with different sine frequencies and watch the frequency spectrum.

You can observe aliasing. Make A2 zero and F1 50 Hz. Run the transform and a line will appear a 50 Hz. Make F1 1050,2050.. and the line will always be 50Hz. Aliasing Where the sampling frequency fs in the code is 1000. In a measurement system there would be an electrical low pass filter to prevent aliasing

On the other had intentional aliasing is used to translate a band of frequencies to another band.

The main difference between the forward and inverse transform is the sign of the exponent.

Code:
#DFT
import math as m
import cmath as cm
import os
import array as ar
os.chdir('c:\\python')

def save_nums(fname,delim,nrows,x,y):
        f = open(fname,'w')
        for i in range(nrows):
                s = "" # row string
                s += repr(x[i]);s += delim;s += repr(y[i]);s += "\n"
                f.write(s)
        f.close()
        return 0

def dftf(n,y,fs,f,mag,yc):
        print("DFT Forwatd Start")
        c2 = 2./n
        fsum = 0
        df = fs/n
        for freq in range(n):
                f[freq] = fsum  # trasform frequency scaling
                fsum +=  df
                c = (2.*m.pi/n) * freq
                sum = 0. + 0.j
                for k in range(n): sum += y[k]*cm.exp(-1.j*c*k)
                if freq == 0:
                        mag[freq] = sum.real/n # averge valuef the waveform
                else:
                        mag[freq] = c2 *abs(sum)
                yc[freq] = sum
        print("DFT Forward Done")

def dftfi(n,yi,yc):
        print("DFT Inverse Start")
        for freq in range(n):
                c = (2*m.pi/n) * freq
                sum = 0 + 0j
                for k in range(n):
                          sum += yc[k]*cm.exp(1.j*c*k)
                yi[freq] = (sum.real/n)
        print("DFT Inverse Trasform Done")

def time_base(n,t,fs):
           dt = 1./fs
           for x in range(n):
                   t[x] = x * dt

def make_pulse(n,a,offset,t,yr,tstart,tstop):
        if tstart < t[0] or tstop > t[n-1] :return 1
        for i in range(n):
                if t[i] >= tstart and t[i] <= tstop:
                        yr[i] = a
                else:
                        yr[i] = offset
        return 0               

def make_sin(n,y,t,f1,f2,a1,a2,os):
    for i in range(n):
        y1 = a1*m.sin(2*m.pi*f1*t[i])
        y2 = a2*m.sin(2*m.pi*f2*t[i])
        y[i] = y1 + y2 + os
      

N = int(m.pow(2,12)) #transform size power of 2
A1 = 1         # signal amplitude and frequency
A2 = 10     
F1 = 1
F2 = 10
tstart = .3     # pulse width seconds
tstop = .8
offset = 5     # signal offset

t  = ar.array('d',N*[0])       # time
yr = ar.array('d',N*[0])      # real signal to transform
yi = ar.array('d',N*[0])       # reconstructed signal from inverse transform
yc = N*[complex(0,0)]      # complex transform
mag = ar.array('d',N*[0])     # spectrum magnitude
f = ar.array('d',N*[0])          # frequncy spectrum
fs = 1000.     # sampling frequency

time_base(N,t,fs)
make_sin(N,yr,t,F1,F2,A1,A2,offset)
#make_pulse(N,A1,offset,t,yr,tstart,tstop)

dftf(N,yr,fs,f,mag,yc)
dftfi(N,yi,yc)

save_nums("sig.dat"," ",N,t,yr)
save_nums("mag.dat"," ",int(N/2),f,mag)
save_nums("sigi.dat"," ",N,t,yi)

os.system("plot.plt")  # invoke Gnuplot

plot.plt

Code:
set term windows 
set multiplot layout 1,3 rowsfirst

set zeroaxis
plot 'sig.dat' with lines ls 4 lt  -1 lw 3

set zeroaxis
plot 'sigi.dat' with lines ls 4 lt -1 lw 3

set zeroaxis
plot 'mag.dat' with impulses ls 4 lt -1 lw 2

unset multiplot
 
Back
Top Bottom