Python 将 pi 打印到小数位数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45416626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:00:12  来源:igfitidea点击:

Print pi to a number of decimal places

pythonpi

提问by Fraser

One of the challenges on w3resources is to print pi to 'n' decimal places. Here is my code:

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)

For whatever reason, it automatically prints pi without taking into account of any inputs. Any help would be great :)

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

回答by Moses Koledoye

Why not just formatusing number_of_places:

为什么不只是format使用number_of_places

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

And more generally:

更普遍的是:

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

In your original approach, I guess you're trying to pick a number of digits using number_of_placesas the control variable of the loop, which is quite hacky but does not work in your case because the initial number_of_digitsentered by the user is never used. It is instead being replaced by the iteratee values from the pistring.

在您的原始方法中,我猜您正在尝试选择一些数字number_of_places作为循环的控制变量,这很棘手,但在您的情况下不起作用,因为number_of_digits从未使用用户输入的初始值。它被替换为pi字符串中的 iteratee 值。

回答by Jonas Adler

The proposed solutions using np.pi, math.pi, etc only only work to double precision (~14 digits), to get higher precision you need to use multi-precision, for example the mpmath package

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

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

Using np.pigives the wrong result

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

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

Compare to the true value:

与真实值比较:

3.14159265358979323846264338327...

回答by cdlane

Your solution appears to be looping over the wrong thing:

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

for number_of_places in fraser:

For 9 places, this turns out be something like:

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

for "9" in "3.141592653589793":

Which loops three times, one for each "9" found in the string. We can fix your code:

循环 3 次,每一个在字符串中找到的“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)

But this still limits nto be less than the len(str(math.pi)), less than 15 in Python 2. Given a serious n, it breaks:

但这仍然限制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
> 

To do better, we have to calculate PI ourselves -- using a series evaluation is one approach:

为了做得更好,我们必须自己计算 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")])

Now we can take on a large value of n:

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

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

回答by vedang_joshi

As this question already has useful answers, I would just like to share how i created a program for the same purpose, which is very similar to the one in the question.

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

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)

Thanks for Reading.

谢谢阅读。

回答by Abhishek Bahukhandi

For example the mpmathpackage

例如mpmath

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

回答by sai krishna

Why not just use:

为什么不使用:

import numpy as np

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

回答by SJ44

This is what I did, really elementary but works (max 15 decimal places):

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