π\piπ的计算公式
代码
#include <iostream>
#include <corecrt_math_defines.h>
#include <iomanip>double compute_pi(int N) //计算pi函数
{double dx = 1.0 / N;double pi = 0;for (int i = 1; i < N; ++i){pi += 2 * sqrt(1 - i * dx*i*dx); // 积分函数}pi += 1;pi *= 2 * dx;return pi;
}int main()
{std::cout << "Please input a number: ";int N = 0;std::cin >> N;double pi = compute_pi(N);std::cout.setf(std::ios::scientific);std::cout << "The computing value of π is " << std::setprecision(10)<<pi << '\n';std::cout << "The computing error is " << std::setprecision(10) << abs(pi - M_PI) << '\n';std::cout << "Please input a tolerance: ";double dtol = 0;std::cin >> dtol; // 输入误差精度,例如 0.000001int M = (int)sqrt(dtol) / dtol; // 以 √dtol / dtol 作为初始的 N 的估计值,记为Mpi = compute_pi(M);while (abs(pi - M_PI) > dtol) // 若计算误差大于输入的容忍误差,则递增M{M += (int)1/sqrt(dtol); // 递增的步进为 1 / √dtol,此处可根据程序运行快慢进行调整pi = compute_pi(M); // 再次计算π值}std::cout << "The computing error is " << std::setprecision(10) << abs(pi - M_PI) << '\n';std::cout << "The number of intervals is " << M << '\n';
}