Wrong cosine values in Python

1.1k views Asked by At

I'm doing a simulation of an integral by taking numbers between 0 and 1, so I can get a force components. But I always get wrong cosine values, for example, when I take a=1 (so it makes a 45ยบ angle, and therefore "L" should be equal to "k"), I get a "k" bigger than "L".If someone can please look what's wrong I'd really apreciate.

from math import pi, sin,cos, atan
for n in s:
    f=atan(n/a)
    L=ko*(Q/N*)*cos(f)
    k=ko*(Q/N)*sin(f)
    y.append(k)
    x.append(L)
yy=sum(y)
xx=sum(x)
print (xx,yy)
2

There are 2 answers

3
DarthSpeedious On

You should use np.array initialized to zero if you want to deal with big arrays (just a suggestion, it is working either way, i prefer to use arrays):

#from math import pi, sin,cos, atan 
import numpy as np 
a=1                 #float( input("Introduce distance: ")) 
N=10                #float( input("Introduce number of charges: ")) 
Q=10**-8 
s=np.linspace (0,1,N)
y=np.zeros(N)
x=np.zeros(N) 
z=np.zeros(N) 
ko=1/(4*np.pi*8.8542*10**-12)
for n in s: 
    f=np.arctan(n/a) 
    L=ko*(Q/(N*(a**2+n**2)))*np.cos(f) 
    k=ko*(Q/(N*(a**2+n**2)))*np.sin(f) 
    E=ko*(Q/(N*(a**2+n**2))) 
    z[n]=E 
    y[n]=k 
    x[n]=L 

zz=sum(z) 
yy=sum(y) 
xx=sum(x) 
print (x,y)       #xx
print(z)          #zz

The small difference that is there is because of float cannot hold more precise value. You can use np.pi/4 in place of f to get same values. If you want to use higher precision values, see this answer. If you want to simulate integration you might have to look into monte carlo simlations.

1
Ami Tavory On

You're aware of the fact that it's in radians, right?

In [4]: math.cos(45)
Out[4]: 0.5253219888177297

In [5]: math.cos(45 / 180. * math.pi)
Out[5]: 1.0