python 将pi打印到小数位数

blpfk2vs  于 2023-09-29  发布在  Python
关注(0)|答案(9)|浏览(162)

w3resources面临的一个挑战是将pi打印到小数点后的n位。下面是我的代码:

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

不管出于什么原因,它会自动打印pi,而不考虑任何输入。任何帮助都会很好:)

4sup72z8

4sup72z81#

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

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

使用np.pi得到错误的结果

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

与真实值比较:

  1. 3.14159265358979323846264338327...
3wabscal

3wabscal2#

为什么不直接使用number_of_places

  1. ''.format(pi)
  2. >>> format(pi, '.4f')
  3. '3.1416'
  4. >>> format(pi, '.14f')
  5. '3.14159265358979'

更一般地说:

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

在你最初的方法中,我猜你试图使用number_of_places作为循环的控制变量来选择一个数字,这是非常古怪的,但在你的情况下不起作用,因为用户输入的初始值number_of_digits从未被使用过。相反,它被pi字符串中的iteratee值替换。

nwsw7zdq

nwsw7zdq3#

例如mpmath

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

pgpifvop4#

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

  1. #import multp-precision module
  2. from mpmath import mp
  3. #define PI function
  4. def pi_func():
  5. while True:
  6. #request input from user
  7. try:
  8. entry = input("Please enter an number of decimal places to which the value of PI should be calculated\nEnter 'quit' to cancel: ")
  9. #condition for quit
  10. if entry == 'quit':
  11. break
  12. #modify input for computation
  13. mp.dps = int(entry) +1
  14. #condition for input error
  15. except:
  16. print("Looks like you did not enter an integer!")
  17. continue
  18. #execute and print result
  19. else:
  20. print(mp.pi)
  21. continue

祝你好运伙计!

展开查看全部
ddhy6vgd

ddhy6vgd5#

您的解决方案似乎在错误的事情上循环:

  1. for number_of_places in fraser:

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

  1. for "9" in "3.141592653589793":

它循环三次,每次循环对应字符串中的每个“9”。我们可以修复您的代码:

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

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

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

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

  1. # Rewrite of Henrik Johansson's ([email protected])
  2. # pi.c example from his bignum package for Python 3
  3. #
  4. # Terms based on Gauss' refinement of Machin's formula:
  5. #
  6. # arctan(x) = x - (x^3)/3 + (x^5)/5 - (x^7)/7 + ...
  7. from decimal import Decimal, getcontext
  8. TERMS = [(12, 18), (8, 57), (-5, 239)] # ala Gauss
  9. def arctan(talj, kvot):
  10. """Compute arctangent using a series approximation"""
  11. summation = 0
  12. talj *= product
  13. qfactor = 1
  14. while talj:
  15. talj //= kvot
  16. summation += (talj // qfactor)
  17. qfactor += 2
  18. return summation
  19. number_of_places = int(input("Enter the number of decimal places you want: "))
  20. getcontext().prec = number_of_places
  21. product = 10 ** number_of_places
  22. result = 0
  23. for multiplier, denominator in TERMS:
  24. denominator = Decimal(denominator)
  25. result += arctan(- denominator * multiplier, - (denominator ** 2))
  26. result *= 4 # pi == atan(1) * 4
  27. string = str(result)
  28. # 3.14159265358979E+15 => 3.14159265358979
  29. print(string[0:string.index("E")])

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

  1. > python3 test2.py
  2. Enter the number of decimal places you want: 100
  3. 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067
  4. >
展开查看全部
htrmnn0y

htrmnn0y6#

这就是我所做的,非常初级但有效(最多15位小数):

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

lc8prwob7#

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

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

感谢阅读。

unftdfkk

unftdfkk8#

为什么不直接用途:

  1. import numpy as np
  2. def pidecimal(round):
  3. print(np.round(np.pi, round))
oyjwcjzk

oyjwcjzk9#

对于6位十进制数字,可以使用

  1. print (f"{math.pi:.6f}")

相关问题