zoukankan      html  css  js  c++  java
  • Newton迭代法-C++

    牛顿迭代法:

      设定x*是方程f(x)=0的根,选取x0作为x*的近似值,过点(x0, f(x0))做曲线f(x)=0的切线L,L的方程y=f(x0)+f'(x0)(x-x0),求出L与x轴焦点的横坐标x1=x0-f(x0)/f'(x0),称x1为x*的一次近似值,然后设置x0=x1,重复上面的过程,反复迭代,就可以得到一个比较精确的近似值。

    代码实现:

    #include <iostream>
    #include <list>
    using namespace std;
    
    /*
        定义一个list列表存储方程的表达式    
    */
    typedef list<double> Expression; 
    
    /*
        方程系统的初始化:
            n为方程的最高项次数
            第一个输入的为常数项的系数
            第二个输入的为x项的系数
            第三个输入的位x平方的系数
            。。。。如此类推
    */
    void Init(Expression *expression) {
        double n;
        double temp;
        cin>>n;
        for(int i = 1; i <= n+1; i++) {
            cin>>temp;
            expression->push_back(temp);
        }
    }
    
    /*
        拿到x的number次方的值
    */
    double GetValue(int number, double x) {
        double sum = 1;
        for(int i = 1; i <= number; i++) {
            sum *= x;
        }
        return sum;
    }
    
    /*
        求导数的值:
            x为变量的值
            expression为表达式
    */
    double DerivativeValue(double x, Expression *expression) {
        double value = 0;
        int i = 0;
        if(!expression->empty()) {
            for(Expression::iterator it = expression->begin(); it != expression->end(); it++) {
                if(i != 0) {
                    value += (*it)*i*GetValue(i, x);    
                }
                i++;
            }
            return value;
        }
        return 0;
    }
    
    /*
        求函数的值
            x为变量的值
            expression为表达式
    */
    double GetFunctionValue(double x, Expression *expression) {
        double value = 0;
        int i = 0;
        if(!expression->empty()) {
            for(Expression::iterator it = expression->begin(); it != expression->end(); it++) {
                value += (*it)*GetValue(i, x);
                i++;
            }
            return value;
        }
        return 0;
    }
    
    /*
        牛顿迭代法:
            expression为表达式
            x0为初始值
            time为你迭代的次数
    */
    double NewtonIterator(Expression *expression, double x0, int time) {
        for(int i = 1; i <= time; i++) {
            x0 = x0 - GetFunctionValue(x0, expression)/DerivativeValue(x0, expression);
        }
        return x0;
    }
    
    int main() {
        Expression *expression = new Expression();
        Init(expression);
        cout<<NewtonIterator(expression, 1, 10)<<endl;
        return 0;
    }
  • 相关阅读:
    494. Target Sum 添加标点符号求和
    636. Exclusive Time of Functions 进程的执行时间
    714. Best Time to Buy and Sell Stock with Transaction Fee有交易费的买卖股票
    377. Combination Sum IV 返回符合目标和的组数
    325. Maximum Size Subarray Sum Equals k 和等于k的最长子数组
    275. H-Index II 递增排序后的论文引用量
    274. H-Index论文引用量
    RabbitMQ学习之HelloWorld(1)
    java之struts2的数据处理
    java之struts2的action的创建方式
  • 原文地址:https://www.cnblogs.com/rayguo/p/3592412.html
Copyright © 2011-2022 走看看