Beginner in C.
I working on exercise to find roots of a function f(x) with newton method.
This is my code:
float bisection_root(float a, float b, float delta) {
// TODO > pass functions ?
// TODO check f(a) * f(b) < 0 o non finisce mai...
//
float func(float x);
printf("test %f \n", func(a) * func(b) );
// mean:
float mean = (a + b) / 2.0;
if ( fabs(func(mean)) < delta) {
printf("Called function is: %s. Found delta. Result: %f\n",__func__, mean);
return mean;
}
else
// check if a, mean have same signs:
if ((func(a) * func(mean)) < 0) {
printf("Called function is: %s. Taking first half. Result: %f %f\n",__func__, delta, func(a) * func(mean));
return bisection_root(a, mean, delta);
}
else {
printf("Called function is: %s. Taking second half. Result: %f %f\n",__func__, delta, func(mean) * func(b));
return bisection_root(mean, b, delta);
}
}
float func(float x) {
return 2*pow(x,3) - 4*x + 1;
}
and called in main like:
int main(int argc, char *argv[]) {
bisection_root(0, 1, 0.00000000002);
return 0;
}
The result is that recursion does not stop, and I have a segmentation fault: 11
.
Could you help in understanding why recursion fail and where is that "program writes out of memory" ?
What does negative zero means in C ?
This is my output:
Called function is: bisection_root. Taking first half. Result: 0.000000 -0.750000
test -0.750000
Called function is: bisection_root. Taking second half. Result: 0.000000 -0.023438
test -0.023438
Called function is: bisection_root. Taking first half. Result: 0.000000 -0.012329
...
Called function is: bisection_root. Taking first half. Result: 0.000000 -0.000000 0.258652
test -0.000000
Called function is: bisection_root. Taking first half. Result: 0.000000 -0.000000 0.258652
test -0.000000
Called function is: bisection_root. Taking first half. Result: 0.000000 -0.000000 0.258652
Segmentation fault: 11