This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Type: Wrong value of pi for larger values using math.cos() function behavior resolved Python 3.7
process
Status: Resolution: closed not a bug darshan.kanade, mark.dickinson normal

Created on 2022-01-20 06:25 by darshan.kanade, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (7)
```I was solving this problem to find the approximate value of pi using the Archimedes method using two different logics -

1) The first one used the formula pi = k*cos(90-180/k) but when I gave very large input, say k=2**62 sides of polygon, then it gives the value of pi as 282.3843260569851... for comparatively smaller k=1000000 it is around 3.14

2)Because the first one was giving wrong answer for larger values, I googled for solution and came across this other logic using the formula pi = k * sin(180/k).
In this method, we get values of pi around 3.14 no matter how large the input is, even if it is k=2**62!```
msg411006 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * Date: 2022-01-20 06:39
`Arguments of cos() and sin() should be in radians, not in degrees. So the correct formulas are k*cos(pi/2-pi/k) and k*sin(pi/k). They are useless because to find the pi approximation you need to know pi.`
```In the program, I did convert degrees to radians
So, this was what I used-
where k=2**62```
msg411008 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * Date: 2022-01-20 07:10
```Yes, math.radians() just multiplies its argument by pi/180.

```The issue is that pi = k*math.cos(math.radians((90 - 180/k))) is giving wrong answer(289.384326...) for larger values of k, say k=2**62, but for smaller values say, k=1000000 it is giving correct answer(3.14....)

pi = k*math.sin(math.radians(180/k)) on the other hand gives correct answer for any value of k (be it k=2**62 or k=1000000)```
msg411011 - (view) Author: Mark Dickinson (mark.dickinson) * Date: 2022-01-20 08:10
```Hi Darshan. This isn't a bug in Python. You're running into the limitations of floating-point arithmetic.

There's a lot of good material on those limitations available on the web, starting with Python's own tutorial: https://docs.python.org/3/tutorial/floatingpoint.html

If you want to understand what's going on in this particular case, take a closer look at the values of 90 - 180/k when k=2**62 and k=2**63, say. Are they the same? Should they be? Why / why not?```
`Thanks Mark, for the explanation. I had no idea about how the floating point values are represented as binary fractions in the computer hardware. It was a very informative document. Thanks again!`
History
Date User Action Args
messages: + msg411014
2022-01-20 08:10:48mark.dickinsonsetstatus: open -> closed

nosy: + mark.dickinson
messages: + msg411011

resolution: not a bug