牛顿法求sinx极值点(C++)
一个比较粗糙的demo,sinx的极值点没有规定范围
#include <iostream>
#include <cmath>
const double DERIV_STEP = 1e-5;//求导的delta x
const double EPSILON = 1e-12;//阈值
const int ITER_TIMES = 40;//最大迭代次数
void Func(const double& x, double &y){
//sin(x)
y = sin(x);
}
void Deriv(void (*Func)(const double& x, double& y), const double& input, double& output){
//求一阶导数
double x1=input-DERIV_STEP, x2 = input+DERIV_STEP;
double y1, y2;
Func(x1, y1);
Func(x2, y2);
output = (y2-y1)/(2*DERIV_STEP);
}
void Deriv2(const double& x, double& y){
//求二阶导数
double yd1, yd2;
Deriv(Func, x-DERIV_STEP, yd1);
Deriv(Func, x+DERIV_STEP, yd2);
y = (yd2 - yd1)/(2*DERIV_STEP);
}
void Newton(const double& init, const double& Epsilon, const int& Times,double& result){
double x = init, yd, yd2;
Deriv(Func, x, yd);
for (int i = 0; (i < Times) && (fabs(yd)>=Epsilon); ++i) {
Deriv(Func, x, yd);
Deriv2(x, yd2);
double temp = yd/yd2;
x-=temp;
}
result = x;
}
int main() {
double x = 0.01, yd, yd2, mX;
Deriv(Func, x, yd);
Deriv2(x, yd2);
Newton(x, EPSILON, ITER_TIMES, mX);
std::cout<<"The derivation of sin(x) at "<<x<<" is "<<yd<<std::endl;//测试导数函数是否正确
std::cout<<"The 2-order derivation of sin(x) at "<<x<<" is "<<yd2<<std::endl;//测试二阶导数是否正确
std::cout<<"The min/max is at "<<mX<<std::endl;
return 0;
}
输出(前两行请忽略)
The derivation of sin(x) at 0.01 is 0.99995
The 2-order derivation of sin(x) at 0.01 is -0.00999983
The min/max is at 98.9602