如何通过长尾词巧妙计算π的值?
- 内容介绍
- 文章标签
- 相关推荐
本文共计328个文字,预计阅读时间需要2分钟。
为了计算π,可以使用等式:pi/4=1 - (1/3)(1/5) + (1/7)(1/9) - ...。这可以转化为一个递归公式。以下是用Python实现该公式的代码:
pythondef calculate_pi(n): pi_over_4=0 for i in range(1, n+1): pi_over_4 +=(-1)**(i+1) / (2*i - 1) return 4 * pi_over_4
示例:计算前5项的和print(calculate_pi(5))
要计算Pi,您可以使用等式pi / 4 = 1-(1/3)(1/5) – (1/7)…乘以4,你得到Pi
我创建了一个公式来计算方程相对于其位置1 /(2n-1)的每一步,并为其编写代码
#include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { double p = 0; double pi = 0; int j = 1; do { if (j % 2 == 1) { p = p + (1 / (2 * j - 1)); } else { p = p - (1 / (2 * j - 1)); } pi = p * 4; printf("%lf\n", pi); j++; } while (j < 10); return (EXIT_SUCCESS); }
但它只是推出4.0000
为什么?我找不到我犯的错误.
替换声明
p = p + (1 / (2 * j - 1));/* 1/(2*j-1) results in integer, you won't get expected result */
同
p = p + (1. / (2 * j - 1));/* 1. means making floating type */
本文共计328个文字,预计阅读时间需要2分钟。
为了计算π,可以使用等式:pi/4=1 - (1/3)(1/5) + (1/7)(1/9) - ...。这可以转化为一个递归公式。以下是用Python实现该公式的代码:
pythondef calculate_pi(n): pi_over_4=0 for i in range(1, n+1): pi_over_4 +=(-1)**(i+1) / (2*i - 1) return 4 * pi_over_4
示例:计算前5项的和print(calculate_pi(5))
要计算Pi,您可以使用等式pi / 4 = 1-(1/3)(1/5) – (1/7)…乘以4,你得到Pi
我创建了一个公式来计算方程相对于其位置1 /(2n-1)的每一步,并为其编写代码
#include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { double p = 0; double pi = 0; int j = 1; do { if (j % 2 == 1) { p = p + (1 / (2 * j - 1)); } else { p = p - (1 / (2 * j - 1)); } pi = p * 4; printf("%lf\n", pi); j++; } while (j < 10); return (EXIT_SUCCESS); }
但它只是推出4.0000
为什么?我找不到我犯的错误.
替换声明
p = p + (1 / (2 * j - 1));/* 1/(2*j-1) results in integer, you won't get expected result */
同
p = p + (1. / (2 * j - 1));/* 1. means making floating type */

