Search code examples
python-2.7python-3.xmathpi

Sin pi : give wrong result


i tried to create polar array with math module ; but math.sin(math.pi) always give wrong result. with python 2.7 or 3.5 the same wrong result :

import math
m = math.radians(180)
print (math.sin(m))
pi = math.pi
print (pi)
print (math.sin(pi))

1.2246467991473532e-16
3.141592653589793
1.2246467991473532e-16

this is my code and the same error:

import math

a = 180 #(degree)

r = 10
n = 8
b = float(a)/n

pi = math.radians(180)
print math.sin(pi)

for i in range(0,2*n+1):
   print i
   c1 = b*i
   print c1
   c2 = c1*math.pi/a #c : radians
   print c2
   sinb = math.sin(c2)
   cosb = math.cos(c2)
   x = r*sinb
   y = r*cosb
   #print (x, y)

the threads mentioned in the comment give explanation not a solution ; so i don't need explanation how and why without solution to solve my problem and the answer from cody give me the solution. if you think that the other threads show the answer mention in these threads that are duplicate.


Solution

  • Since pi is an irrational number and goes on forever, the Python version is not actually exact pi. As a result, the sin of almost-pi is almost-0. Basically you can chalk it up to a Python rounding error.

    Here's some more information on the topic in general:

    Floating Point Arithmetic: Issues and Limitations

    why am I getting an error using math.sin(math.pi) in python?

    I suggest you put some rounding in to the nearest N units that will suffice for your module. The numerical value of what you got is 0.000000000000000122. Five digits after the decimal should be good for almost anything you could need the module for.