[英]C++ Finding root of the function
我被要求找到以下函数的根
sin((a*x / (1 + pow(x, 2))) + 1) * atan(b*x - 1 / 2) + exp(-c*x) * atan(x)
对于两组值
a=10
, b=2
和c=0
a=4.5
, b=2.8
和c=1
但是我没有得到需要在其中找到根的开始和结束值。 我该如何进行?
注意:atan()表示tan的反函数。
程式码片段:
double f(double x, double a, double b, double c)
{
return sin((a*x / (1 + pow(x, 2))) + 1) * atan(b*x - 1 / 2) + exp(-c*x) * atan(x);
}
double RootFinder(double f(double, double, double, double), double a, double b, double c, double left, double right, double precision)
{
double f_left = f(left, a, b, c), now = left + precision, f_right = f(now, a, b, c);
while (f_left * f_right > 0 && now < right)
{
f_left = f_right;
now += precision;
f_right = now;
}
return now - precision / 2;
}
您的函数实现中存在一个错误。
atan(b*x - 1 / 2)
项1 / 2
整数除法并求值为0,这可能不是您想要的。 通常,在对双变量进行算术运算时,请使用双字面量。 pow()
函数确实将(double, int)
作为其重载之一,因此您在这里表现出色。 它也有一个(double, double)
重载,但是如果您的指数实际上是一个整数,那么您就不需要它。
这是最简单的根查找方法(二分法)的简单实现(此后我注意到OP使用了二分法标记,很完美)。
#include <iostream>
#include <cmath>
#include <random>
double f(const double x, const double a, const double b, const double c)
{
return sin((a*x / (1.0 + pow(x, 2))) + 1.0) * atan(b*x - 1.0 / 2.0) + exp(-c*x) * atan(x);
}
double BisectionMethod(
double f(double, double, double, double),
const double a, const double b, const double c,
const std::random_device::result_type entropy)
{
std::mt19937 gen(entropy);
static const auto lower_bound = -1.0;
static const auto upper_bound = 1.0;
std::uniform_real_distribution<> dis(lower_bound, upper_bound);
auto pos_pt = dis(gen);
auto neg_pt = dis(gen);
while (f(pos_pt, a, b, c) < 0.0)
pos_pt = dis(gen);
while (f(neg_pt, a, b, c) > 0.0)
neg_pt = dis(gen);
static const auto about_zero_mag = 1E-8;
for (;;)
{
const auto mid_pt = (pos_pt + neg_pt)/2.0;
const auto f_mid_pt = f(mid_pt, a, b, c);
if (fabs(f_mid_pt) < about_zero_mag)
return mid_pt;
if (f_mid_pt >= 0.0)
pos_pt = mid_pt;
else
neg_pt = mid_pt;
}
}
int main()
{
double a, b, c;
std::random_device rd;
static const auto entropy = rd();
a =10, b = 2.0, c = 0.0;
const auto root1 = BisectionMethod(f, a, b, c, entropy);
std::cout << "a = " << a << ", b = " << b << ", c = " << c << std::endl;
std::cout << "Found root: (" << root1 << ", " << f(root1, a, b, c) << ")" << std::endl;
a =4.5, b = 2.8, c = 1.0;
const auto root2 = BisectionMethod(f, a, b, c, entropy);
std::cout << "a = " << a << ", b = " << b << ", c = " << c << std::endl;
std::cout << "Found root: (" << root2 << ", " << f(root2, a, b, c) << ")" << std::endl;
}
输出 :
g++ -O3 -std=c++11 -Wall -Wextra -pedantic main.cpp -o root && ./root
a = 10, b = 2, c = 0
Found root: (0.143042, -2.12425e-09)
a = 4.5, b = 2.8, c = 1
Found root: (0.136172, 5.81247e-09)
每次运行都会改变输出,因为这使用了RNG。 视觉上输出看起来正确。
该代码假定根由-1.0和1.0限制,在您的情况下为true。 如果您希望它更通用,则需要添加逻辑来处理溢出和检查nan。 如果根不在-1.0到1.0之间,它将永远循环。 尽管如此,它解决了该问题中的特定问题,并且是更一般的东西的开始。
还要注意,您的函数具有多个根,并且给定的代码仅找到一个根。
编辑:清理代码。 在BisectionMethod()
添加了entropy
作为自变量,因此它是可重现的,这在我们谈论数值方法时似乎很理想。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.