math module broken?

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Sat Jul 24 15:13:00 EDT 2004


Dan Sommers wrote:

> On 23 Jul 2004 23:00:18 -0700,
> danb_83 at yahoo.com (Dan Bishop) wrote:

>>def mysin(x):
>>   return math.sin(math.radians(x % 360))
> 
> Why?
> 
>>>>for x in range( 20 ):
> 
>      print '%.12f %.12f' % (math.sin( math.radians( x ) ), math.sin( math.radians( x % 360 ) ))
> 
> 0.000000000000 0.000000000000
> 0.017452406437 0.017452406437
> 0.034899496703 0.034899496703
> 0.052335956243 0.052335956243
> 0.069756473744 0.069756473744
> 0.087155742748 0.087155742748
> 0.104528463268 0.104528463268
> 0.121869343405 0.121869343405
> 0.139173100960 0.139173100960
> 0.156434465040 0.156434465040
> 0.173648177667 0.173648177667
> 0.190808995377 0.190808995377
> 0.207911690818 0.207911690818
> 0.224951054344 0.224951054344
> 0.241921895600 0.241921895600
> 0.258819045103 0.258819045103
> 0.275637355817 0.275637355817
> 0.292371704723 0.292371704723
> 0.309016994375 0.309016994375
> 0.325568154457 0.325568154457

 >>> for x in range(10000000, 10000020): print '%.12f %.12f' % 
(math.sin( math.radians( x ) ), math.sin( math.radians( x % 360 ) ))

-0.984807753010 -0.984807753012
-0.981627183449 -0.981627183448
-0.978147600733 -0.978147600734
-0.974370064789 -0.974370064785
-0.970295726278 -0.970295726276
-0.965925826288 -0.965925826289
-0.961261695942 -0.961261695938
-0.956304755964 -0.956304755963
-0.951056516293 -0.951056516295
-0.945518575604 -0.945518575599
-0.939692620787 -0.939692620786
-0.933580426495 -0.933580426497
-0.927183854571 -0.927183854567
-0.920504853453 -0.920504853452
-0.913545457639 -0.913545457643
-0.906307787041 -0.906307787037
-0.898794046299 -0.898794046299
-0.891006524183 -0.891006524188
-0.882947592863 -0.882947592859
-0.874619707138 -0.874619707139

When the numbers get larger, floats start losing precision. If you 
restrict the numbers to the range [0, 360[ before conversion to radians 
(and hence to degrees), that problem doesn't exist.

-- 
"Codito ergo sum"
Roel Schroeven



More information about the Python-list mailing list