matlab - Solving two nonlinear equations with two unknowns in C++ -
i have 2 nonlinear equations 2 unknowns, i.e., tau
, p
. both equations are: p=1-(1-tau).^(n-1)
, tau = 2*(1-2*p) ./ ( (1-2*p)*(w+1)+(p*w).*(1-(2*p).^m))
.
i interested find value of tau. how can find value using c++ code, have done using matlab , here code 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 @ command window: result=fzero(@tau_eq,[0,1],[])
can 1 me in since new c++. in advance
1.the function fzero solves nonlinear equation rather system of equations.
2.the easiest method method of dichotomy. variant of implementation 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 functions written:
the algorithm, created t. dekker, uses combination of bisection, secant, , inverse quadratic interpolation methods. algol 60 version, improvements, given in brent, r., algorithms minimization without derivatives, prentice-hall, 1973. fortran version, upon fzero based, in forsythe, g. e., m. a. malcolm, , c. b. moler, computer methods mathematical computations, prentice-hall, 1976.
you can implement it.
4.see question: what libraries there solving system of non-linear equations in c++?
Comments
Post a Comment