/*
* @Author: FeiPF2020 wpfn218925@163.com
* @Date: 2022-08-18 01:19:40
* @LastEditors: FeiPF2020 wpfn218925@163.com
* @LastEditTime: 2022-08-18 02:26:08
* @FilePath: \cpp_code\interview\probably_test\Solve_zero.cpp
* @Description:
* 求解一个二次函数的两个根,已知
*
*
* */
#include<iostream>
using namespace std;
/**
* @brief 方法一
* 使用高斯牛顿法求解
* 构造目标函数,y = a*x*x +b*x + c 求解其零点、
* 对应的J是2*(a*x*x +b*x + c)*(2*a + b)
*/
double gauss_Newton(double a, double b, double c,double x){
double J = 2*(a*x*x +b*x + c)*(2*a + b);
//给定迭代次数和对应的误差需求,初始值,
int n = 1000;
double error_ = 1e-7;
int j = 0;
for(int i = 0;i<n;i++){
if(abs(a*x*x +b*x + c)<error_) break;
//梯度下降,不行的,容易跑飞
// x = x - 0.01*J;
//牛顿法
//x = x- (a*x*x +b*x + c)/(2*a + b);
//高斯牛顿法
x = x- (a*x*x +b*x + c)/J;
}
return x;
}
/**
* @brief 二分法求解,给定初值区间[1,3]
*/
double Dichotomy(double a, double b, double c,double m, double n){
//给定初值
double y = 100;
double error_ = 1e-7;
double x = 0;
while(abs(y)>error_){
x = m+(n-m)/2;
y = a*x*x +b*x + c;
if(y>0){
n = x;
}else{
m = x;
}
}
return x;
}
int main(int argc, char const *argv[])
{
double a =1,b =2,c =-4,x =5;
cout<<"gauss_Newton:"<<endl;
cout<<gauss_Newton(a,b,c,x)<<endl;
cout<<"Dichotomy:"<<endl;
cout<<Dichotomy(a,b,c,1,4);
return 0;
}
面试之高斯牛顿和二分求根
最新推荐文章于 2024-11-02 20:20:37 发布