user4871626
user4871626

Reputation: 31

Solving two nonlinear equations with two unknowns in C++

I have two nonlinear equations with two unknowns, i.e., tau and p. both equations are: p=1-(1-tau).^(n-1) and tau = 2*(1-2*p) ./ ( (1-2*p)*(W+1)+(p*W).*(1-(2*p).^m)).

I am interested to find the value of tau. How I can find this value using c++ code, I have done that using MATLAB and here is the code that I used:

function result=tau_eq(tau)

n=6;
W=32;
m=5;

p=1-(1-tau).^(n-1);
result=tau - 2*(1-2*p) ./ ( (1-2*p)*(W+1)+(p*W).*(1-(2*p).^m));

Statement at the command window:
result=fzero(@tau_eq,[0,1],[])

Can some one help me in that since I am new to C++. Thanks in advance

Upvotes: 1

Views: 1814

Answers (1)

user4651282
user4651282

Reputation:

1.The function fzero solves the nonlinear equation rather than a system of equations.

2.The easiest method is a method of dichotomy. This is a variant of its implementation for your equation.

#include <iostream>
#include <cmath>
#include <functional>

std::pair<bool,double> SimpleSolve(std::function<double(double)> &func,
                                   const double xbegin,
                                   const double xend);
int main()
    {
    std::function<double(const double)> func = [](const double &tau)
        {
        auto n=6;
        auto W=32;
        auto m=5;

        auto p=1-pow((1-tau),(n-1));
        return tau - 2*(1-2*p) / ( (1-2*p)*(W+1)+(p*W)*(1-pow((2*p),m)));
        };
    auto R = SimpleSolve(func,0,1);
    if(R.first)
        std::cout<<R.second<<std::endl;
    else 
        std::cout<<"Error"<<std::endl;
    return 0;
    }

std::pair<bool,double> SimpleSolve(std::function<double(double)> &func,
                                   const double xbegin,
                                   const double xend)
    {
    double a=xbegin;
    double b=xend;
    const double epsilon=0.0001;
    const double delta=0.0001;
    double f1=func(a);
    int it=0;
    while(true)
        {
        ++it;
        double c=(b+a)/2;
        if((b-a)<epsilon*2.0)
            return std::make_pair(true,c);

        if(fabs(func(c))<delta)
            return std::make_pair(true,c);
        ((func(a)*func(c))<0) ? b=c : a=c ;
        if(it>1000)
            {
            return std::make_pair(false,c);
            }
        }
    }

3. In Matlab help functions written:

The algorithm, created by T. Dekker, uses a combination of bisection, secant, and inverse quadratic interpolation methods. An Algol 60 version, with some improvements, is given in Brent, R., Algorithms for Minimization Without Derivatives, Prentice-Hall, 1973. A Fortran version, upon which fzero is based, is in Forsythe, G. E., M. A. Malcolm, and C. B. Moler, Computer Methods for Mathematical Computations, Prentice-Hall, 1976.

You can to implement it.

4.See this question: What good libraries are there for solving a system of non-linear equations in C++?

Upvotes: 1

Related Questions