Commit 0c91e4d7 authored by Taddeüs Kroes's avatar Taddeüs Kroes

Finished ass3.

parent 2f7c9750
#include "func_ptr.h" #include "func_ptr.h"
#define MAX_STEPS 1000 double newton_raphson(func_ptr f, func_ptr df, double x_start,
double epsilon, unsigned int *steps, unsigned int max_steps) {
double newton_raphson(func_ptr f, func_ptr df, double x_start, unsigned int *steps) {
double x = x_start, last_x = x - 1; double x = x_start, last_x = x - 1;
for( *steps = 0; x != last_x; (*steps)++ ) { for( *steps = 0; fabs(x - last_x) >= epsilon; (*steps)++ ) {
if( *steps == MAX_STEPS ) if( *steps == max_steps )
return NAN; return NAN;
last_x = x; last_x = x;
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
#include <math.h> #include <math.h>
#include "bisec.h" #include "bisec.h"
#include "newton_raphson.h" #include "newton_raphson.h"
#include "regula_falsi.h"
#define EPSILON 1e-11 #define EPSILON 1e-11
...@@ -17,11 +18,14 @@ double df(double x) { ...@@ -17,11 +18,14 @@ double df(double x) {
int main(void) { int main(void) {
unsigned int steps; unsigned int steps;
printf("Square root of 2 using bisection method: %.11f (%d steps)\n", printf("Square root of 2 using bisection method: %.20f (%d steps)\n",
bisec(&f, 1.4, 1.5, EPSILON, &steps), steps); bisec(&f, 1, 2, EPSILON, &steps), steps);
printf("Square root of 2 using newton_raphson method: %.11f (%d steps)\n", printf("Square root of 2 using Newton-Raphson method: %.20f (%d steps)\n",
newton_raphson(&f, &df, 1.4, &steps), steps); newton_raphson(&f, &df, 1.4, EPSILON, &steps, 100000), steps);
printf("Square root of 2 using the Regula Falsi method: %.20f (%d steps)\n",
regula_falsi(&f, 1, 2, EPSILON, &steps, 100000), steps);
return 0; return 0;
} }
...@@ -38,7 +38,7 @@ int main(void) { ...@@ -38,7 +38,7 @@ int main(void) {
unsigned int steps; unsigned int steps;
double root; double root;
if( !isnan(root = newton_raphson(&f2, &df2, 1000000, &steps)) ) if( !isnan(root = newton_raphson(&f2, &df2, 1000000, EPSILON, &steps, 100000)) )
printf("f2: %.11f (%d steps)\n", root, steps); printf("f2: %.11f (%d steps)\n", root, steps);
else else
printf("f2: could not find a root after %d steps\n", steps); printf("f2: could not find a root after %d steps\n", steps);
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
#include "func_ptr.h" #include "func_ptr.h"
double regula_falsi(func_ptr f, double s, double t, double e, double regula_falsi(func_ptr f, double s, double t, double e,
int *steps, int m) { int *steps, unsigned int m) {
int n, side = 0; int n, side = 0;
double r, fr, fs = f(s), ft = f(t); double r, fr, fs = f(s), ft = f(t);
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment