-1

I'm writing a program that estimates the value of pi. I want to implement that you in the command line can specify when the result have the specified number of correct decimals. Example:

python est_pi.py 3

should end the script when the estimation is 3.141...

Is it possible to have a variable real_pi = 3.14159... and then index into the number of decimals or is there any other solution to this problem?

duen
  • 1
  • 1
  • There are several ways to estimate pi (rather than trying to have it hard coded to as many decimal places as the user may ask for). e.g. https://en.wikipedia.org/wiki/Buffon%27s_needle – doctorlove May 08 '18 at 14:11
  • The lazy solution is to do `real_pi = "3.14159[lots more digits go here]"` and then simply slice the string to your desired length. But that only works for however many characters you put into the string, and I'm guessing you don't want an upper limit. – Kevin May 08 '18 at 14:13
  • It's probably worth mentioning that floats have a limited precision, and even if you calculated pi exactly, a float would only be able to accurately store about fifteen digits after the decimal point. – Kevin May 08 '18 at 14:16

1 Answers1

-1

If You can round your result using:

round(0.333333, N)

Where N is the parameter in input of your script all the details are there: Round float to x decimals?

When you reached the needed precision, you can format the display through:

format(66.66666666666, '.'+str(N)+'f')

That will display your 66.666... with N digits.

In python 3.6 you have the f-string:

value = 2.34558
precision = N
width = 4

print(f'result: {value:{width}.{precision}f}')

Everything is detailed there: Limiting floats to two decimal points

Luc
  • 1,393
  • 1
  • 6
  • 14
  • Every algorithm has a precision, when he reach enough precision (N), he just need to break its algorithm and display the result. The display trick is just there to avoid displaying non-relevant digit. – Luc May 08 '18 at 14:15
  • 1
    `round()` still exists in Python 3 you know, and in Python 2 it does not simply "cut the decimal", read this answer https://stackoverflow.com/questions/13479163/round-float-to-x-decimals/22155830#22155830 – Chris_Rands May 08 '18 at 14:17
  • 1
    thanks for your feedback – Luc May 08 '18 at 14:19
  • No worries :) (not my down vote btw) – Chris_Rands May 08 '18 at 14:31