1

How does Python calculate trigonometric functions? I try to calculate using

x = ((0.1-0.001)/2)*math.sin(((1/20)*math.pi*20)+(0.5*math.pi*1))+((0.1-0.001)/2)+0.001

I'm getting

x = 0.1

why is that? in a usual calculator (radian) i'm getting 0.001

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
tafelrunde
  • 128
  • 2
  • 13

3 Answers3

4

In Python 2, / is integer division,you need to import __future__ .division for floating division :

>>> from __future__ import division
>>> import math
>>> x = ((0.1-0.001)/2)*math.sin(((1/20)*math.pi*20)+(0.5*math.pi*1))+((0.1-0.001)/2)+0.001
>>> x
0.001
Community
  • 1
  • 1
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • 2
    "You need to import `__future__ .division`". Why? – Kevin Mar 18 '15 at 20:23
  • Python 2 casts to integers by default when dividing integers. Python 3 does not, so we can import this floating point functionality. – Malik Brahimi Mar 18 '15 at 20:28
  • @MalikBrahimi yeah! this is one of most basic stuffs in python! i add the link of relative question in SO for OP! that i think its better for OP that could read all the descriptions there! still i get 2 down vote!!!!!!!!!! – Mazdak Mar 18 '15 at 20:35
3

In , python takes the floor of integer division. Thus, you need to import division from the __future__ library at the top of your program.

from __future__ import division
x = ((0.1-0.001)/2)*math.sin(((1/20)*math.pi*20)+(0.5*math.pi*1))+((0.1-0.001)/2)+0.001
print x
Community
  • 1
  • 1
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • 2
    An alternative way is to specify floats when you want a float result. So `1/20` becomes `1.0/20.0` (or `1./20.` or `1./20`). (I did upvote the answer.) You may want to change "python rounds divsion" to "python rounds *integer* division". Actually "rounds" is also not quite right. It takes the floor. – Steven Rumbalski Mar 18 '15 at 20:37
  • @StevenRumbalski which is what my answer says – Vidhya G Mar 18 '15 at 20:41
  • actually only one operand need be a float – joel goldstick Mar 18 '15 at 21:23
1

Just make your integers such as 2 float 2.0, else Python 2.x uses integer division, also known as floor division (rounding towards minus infinity e.g. -9/8 gives -2, 9/8 gives 1), when dividing integers by other integers (whether plain or long):

x = ((0.1-0.001)/2.0)*math.sin(((1/20.0)*math.pi*20)+(0.5*math.pi*1))+((0.1-0.001)/2.0)+0.001

and:

print x
0.001
Vidhya G
  • 2,250
  • 1
  • 25
  • 28