上一次我们说到了这个程序
#include <iostream>
#include <cmath>
#include <limits>
int continuedFractionTerm(int n) {
if (n == 0) return 1;
if (n % 2 == 0) {
return 2 * n + 1;
} else {
return 2 * n;
}
}
std::pair<int, int> bestRationalApproximation(double target, int maxDenominator) {
int numerator = 0;
int denominator = 1;
int prevNumerator = 1;
int prevDenominator = 0;
double bestDiff = std::numeric_limits<double>::max();
for (int i = 0; i < maxDenominator; ++i) {
int term = continuedFractionTerm(i);
int newNumerator = prevDenominator + term * prevNumerator;
int newDenominator = prevNumerator;
prevNumerator = newNumerator;
prevDenominator = newDenominator;
double currentPi = static_cast<double>(newNumerator) / newDenominator;
double diff = std::abs(currentPi - target);
if (diff < bestDiff) {
bestDiff = diff;
numerator = newNumerator;
denominator = newDenominator;
}
}
return {numerator, denominator};
}
int main() {
const double pi_approx = 3.141592653897932384;
int maxDenominator = 100000000;
std::pair<int, int> approximation = bestRationalApproximation(pi_approx, maxDenominator);
std::cout << "最接近π的分数是: " << approximation.first << "/" << approximation.second << std::endl;
std::cout << "差异是: " << std::abs(static_cast<double>(approximation.first) / approximation.second - pi_approx) << std::endl;
return 0;
}
这个是比较快的,还有一个我没测过(准确的说我是没有那个耐心等)
( ̄_, ̄ )
#include <iostream>
#include <cmath>
#include <limits>
int main() {
const double pi_approx = 3.141592653589793; // π的近似值
int numerator = 0; // 分子
int denominator = 1; // 分母
double best_diff = std::numeric_limits<double>::max(); // 初始差异设置为最大double值
// 迭代地检查分数
for (int i = 1; i < 1000000; ++i) { // 限制迭代次数以防止无限循环
for (int j = 1; j < 1000000; ++j) {
double current_pi = static_cast<double>(i) / j; // 当前分数表示的π值
double diff = std::abs(current_pi - pi_approx); // 计算差异
// 如果当前分数更接近π,则更新最佳分数和差异
if (diff < best_diff) {
best_diff = diff;
numerator = i;
denominator = j;
}
}
}
std::cout << "最接近π的分数是: " << numerator << "/" << denominator << std::endl;
std::cout << "差异是: " << best_diff << std::endl;
return 0;
}
长度确实短了一点,但是时间真长。
完!