我需要一些帮助来计算Pi.我正在尝试编写一个将Pi计算为X位数的python程序.我已经尝试过python邮件列表中的几个,这对我的使用来说很慢.我已经阅读了有关Gauss-Legendre算法的内容,我尝试将其移植到Python但没有成功.
我正在读这里,我很感激我输入错误的地方!
输出:0.163991276262
from __future__ import division
import math
def square(x):return x*x
a = 1
b = 1/math.sqrt(2)
t = 1/4
x = 1
for i in range(1000):
y = a
a = (a+b)/2
b = math.sqrt(b*y)
t = t - x * square((y-a))
x = 2* x
pi = (square((a+b)))/4*t
print pi
raw_input()
Run Code Online (Sandbox Code Playgroud) 我正在使用Decimal类进行需要精度的操作.
我想使用'尽可能大'的精度.有了这个,我的意思是程序运行的系统可以处理的精确.
要设置一定的精度,这很简单:
import decimal
decimal.getcontext().prec = 123 #123 decimal precision
Run Code Online (Sandbox Code Playgroud)
我试图找出'Decimal'类可以计算的最大精度:
print(decimal.MAX_PREC)
>> 999999999999999999
Run Code Online (Sandbox Code Playgroud)
所以我试着将精度设置为最大精度(知道它可能不起作用..):
decimal.getcontext().prec = decimal.MAX_PREC
Run Code Online (Sandbox Code Playgroud)
但是,当然,这会引发内存错误(在部门上)
所以我的问题是:我如何计算当前系统可以处理的最大精度?
额外信息:
import sys
print(sys.maxsize)
>> 9223372036854775807
Run Code Online (Sandbox Code Playgroud) 为什么科学记数法中的数字总是被读作a float,如何将像'1e400'这样的字符串转换为a int(对于a来说太大了float)?
>>>int('1e400')
ValueError: invalid literal for int() with base 10: '1e400'
>>>int(float('1e400'))
OverflowError: cannot convert float infinity to integer
Run Code Online (Sandbox Code Playgroud)
我知道,我可以做一个像这样的功能:
def strtoint(string):
parts = string.split('e')
if len(parts) == 1:
return int(string)
elif len(parts) == 2:
if int(parts[1])<0:
return int(string)
return int(parts[0])*10**int(parts[1])
else:
return int(string) #raise a error if the string is invalid, but if the variable string is not a string, it may have other way to convert to an `int`
Run Code Online (Sandbox Code Playgroud)
但这不是一种非常pythonic的方式,有更好的方法吗?