2017-01-09 5 views
10

私は、学校プロジェクトのpiを計算するPython 3プログラムを作成しましたが、常に小数点以下16桁で終了します。 Pythonの数値の長さに制限はありますか?もし私が使うことができる言語があれば、私はそれを続けることができますか?Pythonに数の制限がありますか?

accuracy = int(input("accuracy: ")) 

current = 2 
opperation = "+" 
number = 3 
count = 1 

for i in range (accuracy): 
    if opperation == "-": 
     number = number - (4/(current*(current+1)*(current+2))) 
     opperation = "+" 
    elif opperation == "+": 
     number = number + (4/(current*(current+1)*(current+2))) 
     opperation = "-" 
    current += 2 
    print(str(count).zfill(8)) + ": " + str(number) 
    count += 1 
+2

浮動小数点の不正確さを避けるために、あなたのケースのために重要なのは、長さの制限を回避し、ために 'decimal'モジュールを使用してください。 –

+0

与えられたサイズの浮動小数点数で得られる精度には限界があります。しかし、Pythonはより多くの数字を表示させます: 'from math import pi; print(format(pi、 '.32f')) '。 – jonrsharpe

+0

システム上の浮動小数点の仕様を正確に知りたい場合は、 'import sys; print(sys.float_info) ' –

答えて

9

整数とPython 3.xで作業している場合は制限はありません。しかし、浮動小数点数を使って得られる精度は限られています。あなたが言うようにPythonのfloatは(3.14のような)、実際に精度の約16小数を持つC double、です。

あなたが作成し、任意の精度を持つ他の浮動小数点数で動作するようにdecimalモジュールを使用することができます。コード例:

# Normal Python floats 
a = 0.000000000000000000001 
b = 1 + 2*a 
print(b) # Prints 1.0 

# Using Decimal 
import decimal 
decimal.getcontext().prec = 100 # Set the precision 
a = decimal.Decimal('0.000000000000000000001') 
b = 1 + 2*a 
print(b) # Prints 1.000000000000000000002 

decimalの詳細についてはthe docsを参照してください。

+0

10進数を使用すると、浮動小数点数で表します。 – Richard

+2

@リチャード確かに。 Python 3.3では、 'decimal'モジュールは〜100倍の[sped up](https://docs.python.org/3/whatsnew/3.3.html#new-decimal)でした!新しいバージョンのPythonの場合、それは問題なく遅くなるはずです。 –

+0

私は小数点モジュールのドキュメントでは、piを計算するためのレシピがあることに注意する価値があると思います – Copperfield

関連する問題