牛顿法求sinx极值点(C++)

牛顿法求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

参考
牛顿法与拟牛顿法学习笔记(一)牛顿法

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值