Bisection method in c++

  • Comp Sci
  • Thread starter Sumaya
  • Start date
  • #1
29
0

Homework Statement


find the roots ( interval halving ) , I want to know how to make a condition statement that when fun3 be less than 0.001 and then loop will stop and i get the root .(here in my code i don't know why the loop doesn't work as it should ..


Homework Equations



the equation is : x^3+4x^2-x-1

The Attempt at a Solution



Code:
// UniqueName.cpp : Bisection Method in c++
//

#include "stdafx.h"
#include<iostream>
#include <math.h>
using namespace std;
float fun1(float);
float fun2(float);
float fun3(float);
void main()
{
float a,b,c,a1,b1,c1;
int i=0;
cin>>a>>b;
a1=fun1(a);
b1=fun2(b);
c=(a+b)/2;
c1=fun3(c);
         
           if((a1*b1)<0)
			  do{
				
              if ((a1*c1)<0)
				  b=c;
			  else if((c1*b1)<0)
				  a=c;
			  else
				  break;
			  
			  }
			  while(fabs (c1)<0.01);
			  

		 cout<<"The root  is    "<<c<<endl;
}

		 
float fun1( float a)
{
	float y;
	y=a*a*a+4*a*a-a-1;
	return y;
}
float fun2( float b)
{
	float y;
	y=b*b*b+4*b*b-b-1;
	return y;
}
float fun3( float c)
{
	float y;
	y=c*c*c+4*c*c-c-1;
	return y;
}
thanx in advance
 

Answers and Replies

  • #2
34,905
6,649

Homework Statement


find the roots ( interval halving ) , I want to know how to make a condition statement that when fun3 be less than 0.001 and then loop will stop and i get the root .(here in my code i don't know why the loop doesn't work as it should ..


Homework Equations



the equation is : x^3+4x^2-x-1

The Attempt at a Solution



Code:
// UniqueName.cpp : Bisection Method in c++
//

#include "stdafx.h"
#include<iostream>
#include <math.h>
using namespace std;
float fun1(float);
float fun2(float);
float fun3(float);
void main()
{
float a,b,c,a1,b1,c1;
int i=0;
cin>>a>>b;
a1=fun1(a);
b1=fun2(b);
c=(a+b)/2;
c1=fun3(c);
         
if((a1*b1)<0)
   do{
				
       if ((a1*c1)<0)
         b=c;
      else if((c1*b1)<0)
         a=c;
      else
         break;
   }
   while(fabs (c1)<0.01);
			  
   cout<<"The root  is    "<<c<<endl;
}

		 
float fun1( float a)
{
	float y;
	y=a*a*a+4*a*a-a-1;
	return y;
}
float fun2( float b)
{
	float y;
	y=b*b*b+4*b*b-b-1;
	return y;
}
float fun3( float c)
{
	float y;
	y=c*c*c+4*c*c-c-1;
	return y;
}
Just as in the other thread you started, the logic in your do while loop is backwards. The first time through fabs(c1) > .01, so the loop doesn't do more than one iteration.
 
  • #3
29
0
thank u all <3
 

Related Threads on Bisection method in c++

  • Last Post
Replies
7
Views
4K
  • Last Post
Replies
1
Views
518
  • Last Post
Replies
2
Views
1K
Replies
3
Views
6K
  • Last Post
Replies
2
Views
784
  • Last Post
Replies
2
Views
1K
Replies
4
Views
782
Top