0

I use math.pi with python:

import Decimal as dc
dc.getcontext().prec=100
pi = dc.Decimal(math.pi)

and I get:

3.141592653589793115997963468544185161590576171875

and on Internet, I get:

3,141592653589793238462643383279502884197169399375

Why doesn't python give a good value? How to improve the situation?

I tried with and without Decimal.

martineau
  • 119,623
  • 25
  • 170
  • 301
Romain
  • 11
  • what are you trying to achieve? – sehan2 Jul 10 '21 at 21:40
  • How many decimal places do you need? – quamrana Jul 10 '21 at 21:41
  • `math.pi` is a floating-point value. Taking an existing value and *converting* it to `Decimal` can't possibly add precision that wasn't there to begin with. Use a scientific computing library like `scipy` or `sage` if you need arbitrary precision. – Silvio Mayolo Jul 10 '21 at 21:42
  • Taking an imprecise value and passing that to Decimal isn't going to magically make it more precise. – jonrsharpe Jul 10 '21 at 21:43
  • 4
    The value `math.pi` is a floating point value. It therefore has the same precision as any other ordinary floating point value in Python. Passing it to `Decimal` isn't going to cause it to magically guess what the value is *intended* to be, then fill in the missing digits for you. If you want a higher-precision value for pi than you can get with a `float`, then put the full value in a string. and pass the string to `Decimal`. That way you can get as many digits of precision as you want. You just need to supply them yourself. – Tom Karzes Jul 10 '21 at 21:44

1 Answers1

1

As indicated in the comments and in the documentation of Python math module, math.pi holds a floating-point value. Floating-point is inaccurate by design, because there is a finite number of bits dedicated to keeping the precision. You can read https://docs.python.org/3/tutorial/floatingpoint.html to understand how float is represented, and how this will impact you during programming (in all languages, not only Python).

How to get your accurate value of pi? As mentioned by Tom Karzes, you can use Decimal module and feed it with as many digits as you want. Let's take the first 30 digits of pi from https://www.angio.net/pi/digits/pi1000000.txt, and your code would look like this:

pi_30_decimal_places = Decimal("3.141592653589793238462643383279")

Dharman
  • 30,962
  • 25
  • 85
  • 135
Filip Kubicz
  • 459
  • 1
  • 5
  • 17