求方程解,牛顿迭代和二分

牛顿迭代

#include<iostream>
#include<string.h>
#include<math.h>
using namespace std;
float f(float x){
    return (pow(x,3)-5*pow(x,2)+16*x+80);
}
float f1(float x){
    return (3*pow(x,2)-5*x+16);
}
int main(){
    //  x*x*x-5*x*x+16*x+80;
    float x=1,x1,y1,y2;
    
    cin>>x;
    do{
        x1=x;
        y1=f(x);
        y2=f1(x1);
        x=x1-y1/y2;
        
    }while(fabs(x-x1)>=0.000001);
        cout<<x1<<endl;
        system("pause");

    return 0;
}

如果要计算  根下3  ,则方程为  x*x-3=0;

fabs  对浮点数的取绝对值

用二分法求解方程:

#include<iostream>
#include<math.h>
using namespace std;


double f(double  x){
    return pow(x,x)-10;
}
int main(){
    double a=2,b=3,limit=0.00001;
    while((b-a)>limit){
        if(f((a+b)/2)*f(b)<0){
            a=(a+b)/2;            
        }
        else //同号
            b=(a+b)/2;
    }
    cout<<a<<" "<<b<<endl;
    system("pause");
    return 0;
}

x^x=10;

原文地址:https://www.cnblogs.com/wintersong/p/4399640.html