将 pi 打印到小数位数

  • 本文关键字:小数 pi 打印 python pi
  • 更新时间 :
  • 英文 :


w3resources的挑战之一是将pi打印到小数点后n位。这是我的代码:

from math import pi
fraser = str(pi)
length_of_pi = []
number_of_places = raw_input("Enter the number of decimal places you want to 
see: ")
for number_of_places in fraser:
length_of_pi.append(str(number_of_places))
print "".join(length_of_pi)

无论出于何种原因,它都会自动打印 pi,而不考虑任何输入。任何帮助都会很棒:)

使用np.pimath.pi等的提议解决方案仅适用于双精度(~14 位(,为了获得更高的精度,您需要使用多精度,例如 mpmath 包

>>> from mpmath import mp
>>> mp.dps = 20    # set number of digits
>>> print(mp.pi)
3.1415926535897932385

使用np.pi会给出错误的结果

>>> format(np.pi, '.20f')
3.14159265358979311600

与真实值进行比较:

3.14159265358979323846264338327...

为什么不直接使用number_of_placesformat

''.format(pi)
>>> format(pi, '.4f')
'3.1416'
>>> format(pi, '.14f')
'3.14159265358979'

更一般地说:

>>> number_of_places = 6
>>> '{:.{}f}'.format(pi, number_of_places)
'3.141593'

在您最初的方法中,我猜您正在尝试使用number_of_places作为循环的控制变量来选择一些数字,这非常笨拙,但在您的情况下不起作用,因为用户输入的初始number_of_digits从未使用过。相反,它被替换为pi字符串中的迭代值。

例如mpmath

from mpmath import mp
def a(n):
mp.dps=n+1
return(mp.pi)

很好的答案! 有很多方法可以实现这一点。看看我在下面使用的这种方法,它可以工作任意数量的小数位直到无穷大:

#import multp-precision module
from mpmath import mp
#define PI function
def pi_func():
while True:
#request input from user
try:
entry = input("Please enter an number of decimal places to which the value of PI should be calculatednEnter 'quit' to cancel: ")
#condition for quit
if entry == 'quit':
break
#modify input for computation
mp.dps = int(entry) +1
#condition for input error
except:
print("Looks like you did not enter an integer!")
continue
#execute and print result
else:
print(mp.pi)
continue

祝你好运,朋友!

您的解决方案似乎循环了错误的内容:

for number_of_places in fraser:

对于 9 个地方,结果是这样的:

for "9" in "3.141592653589793":

循环三次,字符串中找到的每个"9"对应一个。 我们可以修复您的代码:

from math import pi
fraser = str(pi)
length_of_pi = []
number_of_places = int(raw_input("Enter the number of decimal places you want: "))
for places in range(number_of_places + 1):  # +1 for decimal point
length_of_pi.append(str(fraser[places]))
print "".join(length_of_pi)

但这仍然限制n小于len(str(math.pi)),在 Python 2 中小于 15。 给定一个严重的n,它中断:

> python test.py
Enter the number of decimal places you want to see: 100
Traceback (most recent call last):
File "test.py", line 10, in <module>
length_of_pi.append(str(fraser[places]))
IndexError: string index out of range
> 

为了做得更好,我们必须自己计算PI - 使用系列评估是一种方法:

# Rewrite of Henrik Johansson's (Henrik.Johansson@Nexus.Comm.SE)
# pi.c example from his bignum package for Python 3
#
# Terms based on Gauss' refinement of Machin's formula:
#
# arctan(x) = x - (x^3)/3 + (x^5)/5 - (x^7)/7 + ...
from decimal import Decimal, getcontext
TERMS = [(12, 18), (8, 57), (-5, 239)]  # ala Gauss
def arctan(talj, kvot):
"""Compute arctangent using a series approximation"""
summation = 0
talj *= product
qfactor = 1
while talj:
talj //= kvot
summation += (talj // qfactor)
qfactor += 2
return summation
number_of_places = int(input("Enter the number of decimal places you want: "))
getcontext().prec = number_of_places
product = 10 ** number_of_places
result = 0
for multiplier, denominator in TERMS:
denominator = Decimal(denominator)
result += arctan(- denominator * multiplier, - (denominator ** 2))
result *= 4  # pi == atan(1) * 4
string = str(result)
# 3.14159265358979E+15 => 3.14159265358979
print(string[0:string.index("E")])

现在我们可以取一个很大的n值:

> python3 test2.py
Enter the number of decimal places you want: 100
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067
> 

这就是我所做的,真的很基本但有效(最多 15 位小数(:

pi = 22/7
while True:
n = int(input('Please enter how many decimals you want to print: '))
if n<=15:
print('The output with {} decimal places is: '.format(n))
x = str(pi)
print(x[0:n+2])
break
else:
print('Please enter a number between 0 and 15')

由于这个问题已经有了有用的答案,我只想分享我如何为相同目的创建一个程序,这与问题中的程序非常相似。

from math import pi
i = int(input("Enter the number of decimal places: "))
h = 0
b = list()
for x in str(pi):
h += 1
b.append(x)
if h == i+2:
break
h = ''.join(b)
print(h)

感谢您的阅读。

为什么不直接使用:

import numpy as np
def pidecimal(round):
print(np.round(np.pi, round)) 

最新更新