Commit c36e9ff8 authored by Taddeüs Kroes's avatar Taddeüs Kroes

Worked on ass4.

parent 22ff97f8
...@@ -4,6 +4,8 @@ ...@@ -4,6 +4,8 @@
#include "func_ptr.h" #include "func_ptr.h"
#define EPSILON 1e-11 #define EPSILON 1e-11
#define MAX_STEPS 1000
#define BISEC_STEPS 5
double bisec_limited(func_ptr f, double left, double right, int max_steps) { double bisec_limited(func_ptr f, double left, double right, int max_steps) {
int i; int i;
...@@ -23,10 +25,13 @@ double bisec_limited(func_ptr f, double left, double right, int max_steps) { ...@@ -23,10 +25,13 @@ double bisec_limited(func_ptr f, double left, double right, int max_steps) {
return mid; return mid;
} }
double newton(func_ptr f, func_ptr df, double x_start, int *steps) { double newton_raphson(func_ptr f, func_ptr df, double x_start, 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; x != last_x; (*steps)++ ) {
if( *steps == MAX_STEPS )
return NAN;
last_x = x; last_x = x;
x -= f(x) / df(x); x -= f(x) / df(x);
} }
...@@ -34,6 +39,10 @@ double newton(func_ptr f, func_ptr df, double x_start, int *steps) { ...@@ -34,6 +39,10 @@ double newton(func_ptr f, func_ptr df, double x_start, int *steps) {
return x; return x;
} }
/*
* Manually define the functions and their derivatives.
*/
double f1(double x) { double f1(double x) {
return x * x - x + 2; return x * x - x + 2;
} }
...@@ -60,8 +69,12 @@ double df3(double x) { ...@@ -60,8 +69,12 @@ double df3(double x) {
int main(void) { int main(void) {
int steps; int steps;
double root;
printf("f1: %.11f (%d steps)\n", newton(&f2, &df2, -100, &steps), steps); if( !isnan(root = newton_raphson(&f2, &df2, 1000000, &steps)) )
printf("f2: %.11f (%d steps)\n", root, steps);
else
printf("f2: could not find a root after %d steps\n", steps);
return 0; return 0;
} }
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