first math demo with release 0.2.0
Reinhard
Posts: 489
Since this weekend I have to learn with my daughter for a math school exercise
this propgcc demo is newly formed:
this propgcc demo is newly formed:
/*
find the zero of a given function
with newton approximation
x(n+1) = x(n) - [ f(xn) / f'(xn) ]
compile : propeller-elf-gcc -mlmm -Os -o newton.elf main.cpp -lm
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef double (*Fct)(double x);
#define MAXSTEP 1000
#define EPS 0.000001
#define START 1.5
////////////////////////////////////
// User Function
////////////////////////////////////
double function (double x)
{
return x*x*x -3*x - 1;
}
////////////////////////////////////
// Differentiate any given Function
// at point x.
////////////////////////////////////
double diff(double (*f)(double), double x)
{
double h = 0.0001;
return (f(x+h)-f(x-h))/(2*h);
}
/////////////////////////////////////
// Newton Approximation
/////////////////////////////////////
int main(int argc, char *argv[])
{
double x = START;
int it = 1;
Fct fct;
fct = function;
do
{
printf("iteration nr. %d xn = %f f(xn) = %f\n",it,x,fct(x));
x = x - ( fct(x) / diff(fct,x) );
it++;
}while (it < MAXSTEP && fabs(fct(x)) > EPS);
if(it >= MAXSTEP)
printf("\nno convergence!\n");
else
printf("iteration nr. %d xn = %f f(xn) = %f\n",it,x,fct(x));
return EXIT_SUCCESS;
}
