python 将pi打印到小数位数

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

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,而不考虑任何输入。任何帮助都会很好:)

4sup72z8

4sup72z81#

建议的使用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...
3wabscal

3wabscal2#

为什么不直接使用number_of_places

''.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字符串中的iteratee值替换。

nwsw7zdq

nwsw7zdq3#

例如mpmath

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

pgpifvop4#

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

#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 calculated\nEnter '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

祝你好运伙计!

ddhy6vgd

ddhy6vgd5#

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

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 ([email protected])
# 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
>
htrmnn0y

htrmnn0y6#

这就是我所做的,非常初级但有效(最多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')
lc8prwob

lc8prwob7#

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

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)

感谢阅读。

unftdfkk

unftdfkk8#

为什么不直接用途:

import numpy as np

def pidecimal(round):
    print(np.round(np.pi, round))
oyjwcjzk

oyjwcjzk9#

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

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

相关问题