[英]python3 calculate N digits of PI python cut the long number
i need to write a script that get input from client of an number and i need to print back the PI number until client number for example: client number is 52 --> 3.14159265358979323846264338327950288419716939937510我需要编写一个脚本来从客户那里获取一个数字的输入,我需要打印回 PI 号码直到客户号码例如:客户号码是 52 --> 3.14159265358979323846264338327950288419716939937510
so far i write this:到目前为止,我是这样写的:
sum = 0
for i in range(1, 1001):
sum += ((-1)**(i+1))*4 / ((i + i)*(i + i + 1)*(i + i + 2))
print(sum)
the issue is that python showing to me only the 17 decimals digits, and i expect to see the 1000 decimal digits.问题是 python 只向我显示 17 位小数,我希望看到 1000 位小数。 there is a way to showing all the decimal digits based on the inputed range?
有没有办法根据输入的范围显示所有十进制数字? it's for school task, so i need to write is as simple as it can be.
这是学校任务,所以我需要写得尽可能简单。
I do not think it is possible to get aa float value with a 1000point precision.我认为不可能获得 1000 点精度的浮点值。
Check https://stackoverflow.com/a/54967370/11152011 to calculate pi up to n-precision检查https://stackoverflow.com/a/54967370/11152011以计算高达 n 精度的 pi
You can then use the "decimal" library to use the string as a number.然后,您可以使用“十进制”库将字符串用作数字。
The calculation of pi was taken from the above link. pi 的计算取自上述链接。
import decimal
DIGITS = 1000
def pi_digits(x):
k,a,b,a1,b1 = 2,4,1,12,4
while x > 0:
p,q,k = k * k, 2 * k + 1, k + 1
a,b,a1,b1 = a1, b1, p*a + q*a1, p*b + q*b1
d,d1 = a/b, a1/b1
while d == d1 and x > 0:
yield int(d)
x -= 1
a,a1 = 10*(a % b), 10*(a1 % b1)
d,d1 = a/b, a1/b1
digits = [str(n) for n in list(pi_digits(DIGITS))]
str_pi='{}.{}'.format(digits.pop(0), "".join(digits)
context = decimal.Context(prec=100)
decimal.setcontext(context)
pi = decimal.Decimal(str_pi)
print(pi+5)
print(pi*20)
I don't know how accurate is this but for a small class assignment i guess do the following:我不知道这有多准确,但对于小班作业,我想请执行以下操作:
num=52 #input
pi=22/7;
print('{:.{}f}'.format(pi, num))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.