Hi all,

I m new to C++ and very desperately looking for some help in my code.Im trying to write a program that uses bisection method to find the root of a function.Im having problems as my results are not accurate enough and my function (f) does not produce answers in required decimal points.

``````#include <iostream>
#include<cdtg>
#include<cstdlib>
using namespace std;

void readParameters(float& x1,float& x2,float& epsilon) {
cout << endl << endl << "The Bisection Method" << endl;
cout << "Please input x1, x2 and epsilon seperated by whitespace: ";
cin >> x1;
cin >> x2;
cin >> epsilon;
cout << endl << endl;
}

float f(float x) {
return (x*x*x)-(3.17*x*x)-(4.835*x)+11.01;
}

void findZero(float& x1,float& x2,float epsilon) {
float low, high, midpoint;
if (f(x1) <= 0) {
low = x1;
high = x2;
}
else {
low = x2;
high = x1;
}

midpoint = low + (high-low)/2;
while (abs(high - low) > epsilon) {
if (f(midpoint) <= 0) {
low = midpoint;
}
else{
high = midpoint;
}
midpoint = low + (high-low)/2;
}
if (low>high)
{
x2=low;
x1=high;
}else{
x1=low;
x2=high;
}
}

int main()
{
float x1 = 0.0;
float x2 = 0.0;
float epsilon = 0.0;

if (x1 > x2)
{
cout<<"Empty interval"<<endl;
return 0;
}

findZero(x1,x2,epsilon);

cout << "Zero is in the interval [x1,x2] = [" << x1 << "," << x2 << "]" << endl;
cout << "f(x1) = " << f(x1) << endl;
cout << "f(x2) = " << f(x2) << endl;
}``````

help me.

Thanks.
Sana

Edited by Nick Evan: added code tags

2
Contributors
1
2
Views
8 Years
Discussion Span
Last Post by vijayan121

Change line 32 to use fabs instead of abs (why?)

``while ( fabs(high - low) > epsilon ) {``

Ideally, also change the type of all the floating point numbers to double instead of float (why?)

And you should be ok.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.