i'm trying to write a program that would find the root of a function using 2 the start and end inputs from a user and using the bisection method.However , it only gives me a root at 0 with f(x) = 50 which is wrong.
Now , the program is pretty lengthy so I only provided the parts needed however if u need the rest ask me.
Code:
/*----------------------------------------------------File: bisectionSearchSoln.c
Description: Applies bisection root finding method.
------------------------------------------------------*/
#include <stdio.h>
#include <math.h>
#include "gng1106plplot.h"
#define N 100 // number of points
#define TRUE 1
#define FALSE 0
#define EPSILON 1e-10
// Function Prototypes
void findInterval(double *, double *);
int findRoot(double, double, double *);
void plotFunc(double, double, int, double []);
double func(double);
void plot(int, double[], double[], int, double[], double[]);
double getMin(double *, int );
double getMax(double *, int );
/*--------------------------------------------------------
Function: main()
---------------------------------------------------------*/
int main()
{
double start, end;
double root;
int n; // number of roots found
// Get intervals from user
findInterval(&start, &end);
printf("Finding root for interval between %.4f and %.4f\n",
start, end);
if(findRoot(start, end, &root))
{
printf("Found root at: %.8f (f(x) = %.8f)\n",root, func(root));
n = 1;
}
else
{
printf("Did not find root in interval.");
n = 0;
}
plotFunc(start, end, n, &root);
return 0;
}
/*----------------------------------------------------------
Function: findRoot
Parameters
lower, upper: lower and upper values of x for the interval
root - pointer to array for saving roots
Returns: TRUE if a root was found (store in root), and FALSE
if no root exists in interval.
Description: Find the root between the interval for the
function using the bisection
method.
---------------------------------------------------------------*/
int findRoot(double lower, double upper, double *root)
{
double x0 , x1 ;
x0=upper;
x1= lower;
int retVal = FALSE;
if(func(x0)*func(x1) > 0)
{
do
{
retVal = TRUE;
*root = (x0+x1)/2;
if(func(*root) > 0 )
x1 = *root;
else x0 = *root;
}while(fabs(*root)< EPSILON);
return(TRUE);
}
}
/*----------------------------------------------------------
Function: func
Parameters:
x - x value function f(x)
Returns: value y of function f(x)
Description: Plots the value of the function:
f(x) = 50 - x^2 |cos(sqrt(x)| , x must be positive, if x
negative return 0.
-----------------------------------------------------------*/
double func(double x)
{
double fx;
if(x < 0)
fx = 0;
fx = 50 - x*x * fabs(cos(sqrt(x)));
return fx;
}