简体   繁体   English

Python 在分数之间交替使用 + 和 -

[英]Python Alternating + and - between fractions

I am trying to use the Nilakantha Pi Series formula and a for loop to calculate pi depending on how far into the calculation the user chooses the iterations to be.我正在尝试使用 Nilakantha Pi Series 公式和 for 循环来计算 pi,具体取决于用户选择迭代的计算深度。 Here is the website that shows this infinite formula: https://www.mathsisfun.com/numbers/pi.html .这是显示这个无限公式的网站: https://www.mathsisfun.com/numbers/pi.html I want to display the correct answer for iterations greater than 1, but only the first iteration shows the correct answer.我想显示大于 1 的迭代的正确答案,但只有第一次迭代显示正确答案。 Here is what I have so far:这是我到目前为止所拥有的:

def for_loop(number):
    n = 4
    pi = 3
    for i in range(1, number + 1):
        den = (n-2) * (n-1) * n
        if (number % 2 == 0):
            pi -= (4 / den)
            print(pi)
        else:
            pi += (4 / den)
            print(pi)
        n = n + 2

The immediate problem is that you are checking if number , not i , is even or odd.直接的问题是您正在检查number ,而不是i ,是偶数还是奇数。 But you don't need any such checks.但是您不需要任何此类检查。 You just have to alternate the numerator between 4 and -4.您只需将分子在 4 和 -4 之间交替。

def for_loop(number):
    n = 4
    pi = 3
    num = 4
    for _ in range(number):
        den = (n-2) * (n-1) * n
        pi += num/den
        print(pi)
        num *= -1
        n += 2

or或者

from itertools import cycle

def for_loop(number):

    n = 4
    pi = 3
    for num in cycle([4, -4]):
        den = (n-2)*(n-1)*n
        pi += num/den
        print(pi)
        n += 2

or even甚至

from itertools import cycle, count

def for_loop(number):
    pi = 3
    for num, n in zip(cycle([4,-4]), count(4, 2)):
        den = (n-2)*(n-1)*n
        pi += num/den
        print(pi)

You have to rework the condition of %2您必须修改 %2 的条件

def for_loop(number):
    n = 4
    pi = 3
    for i in range(1, number + 1):
        den = (n-2) * (n-1) * n
        if (i % 2 == 0):# replace number by i , its alternating between even/uneven, however number is all the time the same.
            pi -= (4 / den)
        else:
            pi += (4 / den)
        print(pi)
        n = n + 2 

This is another way of doing it by using the reduce() function of the functools module, to solve the operation in the denominator of the fraction.这是通过使用functools模块的reduce() function 来解决分数分母中的运算的另一种方法。 To change the sign (-1 or 1) for each iteration, you can just multiply it by -1.要更改每次迭代的符号(-1 或 1),只需将其乘以 -1。

from functools import reduce


def nilakantha(n):
    i, sign, start, base, stop = 1, 1, 2, 3, 4
    res = base
    while i < n and n > 1:
        res += sign * (4 / reduce(lambda x, y: x * y, range(start, stop + 1)))
        sign *= -1
        start = stop
        stop = start + 2
        i += 1
    return res

Example output示例 output

>>> nilakantha(524)
3.141592655327371

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM