can someone please help me?! I have been working on this C++ project forever and I can't seem to get it. I am trying to write a program that will find the root of the following equation using the bisection method:

x(1 + [summation from 1 to M of (Kj*Nj)/(1 + Kj*x)]) - L = 0

where the user inputs a value for M, the different values of Kj and Nj and one value for L.  

i.e. I would input M=2, K1=1, N1=1, K2=2, N2=.5, L=3, etc.  I would be soooo appreciative of any help!  Thanks!

Code:

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

int main () {
    double a, b, TOL, maxiterations;
    double k[20], n[20], L, M, FA, FP;
    cout << "enter M: " << endl;
    cin >> M;
    for (int g = 0; g < M; g++) {
        cout << "enter k: " << endl;
        cin >> k[g];
        cout << "enter n: " << endl;
        cin >> n[g];
    }
    cout << "enter L: " << endl;
    cin >> L;
    cout << "enter a: " << endl;
    cin >> a;
    cout << "enter b: " << endl;
    cin >> b;
    cout << "enter tolerance: " << endl;
    cin >> TOL;
    cout << "enter iterations: " << endl;
    cin >> maxiterations;
    double summationa = 0;
    double summationp = 0;
    for (int h = 0; h < M; h++) {
    summationa += ((k[g] * n[g])/(1.0 + (k[g] * a)));
    double p = a + ((b - a)/2);
    summationp += ((k[g] * n[g])/(1.0 + (k[g] * p)));
    for (int i = 1; i <= maxiterations; i++) {
        //double p = a + ((b - a)/2);
        FP = (p * (1 + summationp)) - L;
        if (FP = 0 || (b - a)/2 < TOL) {
            cout << "root is " << p << endl;
            return 0;
        }
        i = i + 1;
        FA = (a * (1 + summationa)) - L;
        if ((FA * FP) > 0) {
            a = p;
        }
        else {
            b = p;
        }
    }
    }
    cout << "failed after " << maxiterations << " iterations." << endl;
    return 0;
}

Dani AI

Generated

A compact, practical follow‑up to the posts from , and that fixes the typical mistakes and gives a reliable bisection skeleton.

The original attempt trips over a handful of predictable bugs: loop/index variables used out of scope (wrong index when summing), computing the summation and midpoint in the wrong nested loop, using assignment instead of comparison when testing for zero, manually incrementing the for‑loop counter inside the loop, and treating counts (M, maxIterations) as floating types. Also there was no check that the chosen endpoints actually bracket a sign change. Any of those will break the algorithm or produce garbage results.

Checklist and robust approach (brief)

  • Implement one function f(x) that recomputes the full summation for the current x. Do not reuse a summation computed for a different x.
  • Use int (or size_t) for counts and vector<double> sized by M. Validate inputs (M positive, arrays same length).
  • Before iterating ensure f(a) and f(b) have opposite signs (if either is zero return it).
  • Iteration: for iter = 1..maxIter compute mid = 0.5*(a+b), fm = f(mid); stop when |fm| < tol or (b-a)/2 < tol; update the bracket and its stored function value (fa or fb) — do not recompute unnecessary sums.
  • Watch denominators 1 + K_j*x — if any denom ≈ 0 treat it as a singularity and avoid using that x for bracketing.

Example skeleton (new, concise):

double f(double x, const std::vector<double>& K, const std::vector<double>& N, double L) {
    double s = 0.0;
    for (size_t j = 0; j < K.size(); ++j) {
        double d = 1.0 + K[j]*x;
        if (fabs(d) < 1e-15) throw std::runtime_error("singularity near x");
        s += (K[j]*N[j]) / d;
    }
    return x*(1.0 + s) - L;
}

// bisection: compute fa=f(a), fb=f(b); require fa*fb <= 0; then loop updating a/b and fa/fb.

Quick notes for Newton / Picard: Newton needs the derivative
f'(x) = 1 + S(x) - x * sum_j (K_j*K_j*N_j)/(1+K_j*x)^2. A convenient fixed‑point is g(x)=L/(1+S(x)), but always check |g'(root)|<1 before trusting convergence. Bisection remains the safest when denominators or derivatives behave poorly.

Recommended Answers

All 9 Replies

Member Avatar for Member #46692

>I have been working on this C++ project forever and I can't seem to get it.

You have...
http://www.daniweb.com/techtalkforums/thread40264.html

I'm glad to see you ditched the newton/raphson method for an algorithm where you don't have to test your own calculus skills.

However, in order to make this more readable use code tags to properly indent your code.

x(1 + [summation from 1 to M of (Kj*Nj)/(1 + Kj*x)]) - L = 0

x(1+\sum_{j=1}^{M} \frac{k_j*N_j}{1+K_j*x})-L=0

Is dat what you mean it to look like?

yes!!! that is what it is supposed to look like. sorry about the tags, I will use them next time. I actually have to do the newton's method and picard method (fixed point iteration) also for the same function but I feel like once I have this one down, I can do the rest. can you please help me??? thanks!!

>I have been working on this C++ project forever and I can't seem to get it.

You have...
http://www.daniweb.com/techtalkforums/thread40264.html

I'm glad to see you ditched the newton/raphson method for an algorithm where you don't have to test your own calculus skills.

However, in order to make this more readable use code tags to properly indent your code.

x(1 + [summation from 1 to M of (Kj*Nj)/(1 + Kj*x)]) - L = 0

x(1+\sum_{j=1}^{M} \frac{k_j*N_j}{1+K_j*x})-L=0

Is dat what you mean it to look like?

Member Avatar for Member #46692

Sorry,on second thought, the summation function has confused me. I've never worked with root finding algorithms that contain summation thingies. :sad:

Moreover, the example you have given perplexes me further:

i.e. I would input M=2, K1=1, N1=1, K2=2, N2=.5, L=3, etc. I would be soooo appreciative of any help! Thanks!

That is telling me that 'k' increments by one and 'n' decrements by 0.5 at each step. Is that right?


I've only used root finding methods with plain old functions [tex]y=(x-2)(x+3)[/tex].

Second I don't necessarily get why it has changed since your last post. You didn't have a summation thing in there before so where did it creep in?

Third, have you plotted the graph so you can see where the roots are...so you know what values you can choose for [tex]a[/tex] and [tex]b[/tex].

I don't no, maybe someone with more experience can help you.

Well I took a look at your problem. Regarding the bisection-method looks as if you dont have an idea with what you are doing. I will give you a brief algorithm here and try to see if you can understand it and implement it.

Eq is x[ 1 + k1*n1/(1 + k1*x ) + k2*n2/(1 + k2*x ) + ... km*nm/(1 + km*x ) - L = 0 The idea of the bisectional method is to first find two values of x so that the left part of the above equation is positive for one of those values and negative for the other value.

If you take x = 0 as one of the values, by substituting x = 0 to the above equation, the left side will be equal to -L.

So now we have to find another value of x such that the left part of the equation is of opposite sign of -L.

To do this

for ( x = 1 ; x < INT_MAX; x++ )
{
       value = x[ 1 + k1*n1/(1 + k1*x ) + k2*n2/(1 + k2*x ) + ... km*nm/(1 + km*x )  - L ;
       if  ( ( (-L ) > 0 and value < 0 ) or ( ( (-L ) < 0 and value > 0 ) )
       {
             secondvalue = x ;
             break;
       }

	// Maybe -x has a value where the sign changes
	value = (-x)[ 1 + k1*n1/(1 + k1*(-x) ) + k2*n2/(1 + k2*(-x) ) + ... km*nm/(1 + km*(-x) )  - L ;
       if  ( ( (-L ) > 0 and value < 0 ) or ( ( (-L ) < 0 and value > 0 ) )
       {
             secondvalue = (-x) ;
             break;
       }
}

if ( x == INT_MAX )
{
      no value found where the LHS changes signs.
      This means that the function hasnt got roots. at least under the INT_MAX limit.
      return from the function.
      
}
you are here means that you have got a valid value for secondvalue also.

For the rest of the part you can refer this URL.
Bisection Simulation.
Just remember that the first positiveguess and negativeguess pair is the one we found above, i.e 0 and secondvalue.

commented: Wolfffyyyy wocks! +3

i am looking for a c++ programm that finds the root of any function using bisection method.can any body help me with the problem.thank you .

Member Avatar for Member #46692

Sure what have you got so far?

we are given this assignment to be submitted tomorrow so please it would be nice of you if you could write the whole program for us soon

commented: Obviously, http://www.daniweb.com/forums/announcement8-2.html means nothing to you -2
commented: No soup for you! -2
commented: We? Are you 2 associated? +0
Member Avatar for Member #46692

Sorrie can't do that.

Please help with Location of Roots!!

Can someone please help me?! I have been working on a VB6 project and I can't seem to get it. I am trying to write a program that will find the root of a given equation using the following methods
1. Bisection method
2. False Position method
3. Secant Method
4. Newton-Raphson Method

where toll = ten exponent negative 9

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.