2

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)
Bilis
  • 33
  • 4

2 Answers2

5

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
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
0

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.

Community
  • 1
  • 1
DarthSpeedious
  • 965
  • 1
  • 13
  • 25
  • But im getting (63.551473451641151, 26.323789142728536) instead of (63.551500711322454, 63.55150071132246) that is what i'm supposed to get, so I don't think the problem is in the float... But I don't know... :/ – Bilis Jun 16 '15 at 17:15
  • Ok, so your way is actually functional, touché, the components are the same when the angle is 45º but the numbers aren't the ones that I get with the integral. – Bilis Jun 16 '15 at 17:47
  • Integral!? can you please explain, what integration are we talking about? Since your question said charges earlier did you mean continuous integral? – DarthSpeedious Jun 16 '15 at 20:29