find_root_bisec - { /* function to implement bisection...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
/* find_root_bisec.c * Code to find the positive root of f(x)=sin(x)-x/2 using the bisection * method. */ #include <stdio.h> #include <math.h> #define PI 3.14159265 #define EPS 6.e-8 /* roughly machine accuracy */ #define JMAX 40 /* maximum number of iterations */ float rt_bisec(float x1, float x2, float xacc); float f(float x); int main() { float x1, x2, xacc, rt_est, check; x1 = 0.5*PI; x2 = PI; xacc = 0.5*EPS*(fabs(x1) + fabs(x2)); /* convergence criterion */ rt_est = rt_bisec(x1, x2, xacc); /* find root */ printf("Estimate of root x = %f\n", rt_est); check = f(rt_est); /* check root */ printf("f(x) = %g\n",check); return 0; } float f(float x) { float y; y=sin(x)-0.5*x; return y; } float rt_bisec(float x1, float x2, float xacc)
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: { /* function to implement bisection method for root finding */ float f1, f2, fmid, xmid; int j; f1 = f(x1); f2 = f(x2); if (f1*f2 > 0) { printf("Root must be bracketed for bisection\n"); return x1; } for (j = 0; j < JMAX; j++) /* bisection loop */ { printf("%d %f\n", j, x1); xmid = 0.5*(x1 + x2); fmid = f(xmid); if (f1*fmid <= 0) /* root in [x1, xmid] */ { x2 = xmid; f2 = fmid; } else /* root in (xmid, x2] */ { x1 = xmid; f1 = fmid; } if (f1 == 0) return x1; else if (f2 == 0) return x2; else if (fabs(x2 - x1) < xacc) return x1; } printf("Exceeded maximum number of iterations\n"); return x1; }...
View Full Document

This note was uploaded on 09/29/2009 for the course COSC 1002 taught by Professor Wheatland during the Three '09 term at University of Sydney.

Page1 / 2

find_root_bisec - { /* function to implement bisection...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online