diff --git a/hws/hw2/main.c b/hws/hw2/main.c index d940ede..992cdb3 100644 --- a/hws/hw2/main.c +++ b/hws/hw2/main.c @@ -1,20 +1,35 @@ +#include #include #include +#include "muller.h" #include "nr.h" -#include "rtmuller.h" void dbessj0(float x, float *y, float *dy) { *y = bessj0(x); *dy = -bessj1(x); } +float test_func(float x) { + return x * sin(x) - 1; +} + +float test_func_derivative(float x) { + return sin(x) + x * cos(x); +} + +void test_funcd(float x, float *y, float *dy) { + *y = test_func(x); + *dy = test_func_derivative(x); +} + int main() { /* 1. using zbrak, find all possible intervals with roots. 2. and use routines and enumerate all roots. */ - + printf("=== A Program that find bessj0 roots in [1, 10] ===\n"); + printf("--------------------------------\n"); float a = 1.0, b = 10.0; float xacc = 0.000001; @@ -94,6 +109,35 @@ int main() { free(roots_newt); free(roots_newtsafe); free(roots_muller); + printf("\n"); + printf("=== Solve one interesting nonlinear equation ===\n"); + printf(": using the routine of rtsafe.c in NR in C\n"); + printf("--------------------------------\n"); + n = 21; + xb1 = calloc(sizeof(float), n); + xb2 = calloc(sizeof(float), n); + nb = 0; + + zbrak(test_func, a, b, n, xb1, xb2, &nb); + float *roots_interesting = calloc(sizeof(float), nb); + + for (i = 0; i < nb; i++) { + float l = xb1[i + 1]; + float r = xb2[i + 1]; + + roots_interesting[i] = rtsafe(test_funcd, l, r, xacc); + } + + printf("I want to find roots of `x * sin(x) - 1`\n"); + printf("roots: "); + for (i = 0; i < nb; i++) { + printf("%f ", roots_interesting[i]); + } + printf("\n"); + + free(xb1); + free(xb2); + free(roots_interesting); return 0; } \ No newline at end of file diff --git a/hws/hw2/rtmuller.c b/hws/hw2/muller.c similarity index 98% rename from hws/hw2/rtmuller.c rename to hws/hw2/muller.c index 3004228..35f99f5 100644 --- a/hws/hw2/rtmuller.c +++ b/hws/hw2/muller.c @@ -1,6 +1,6 @@ #include "nrutil.h" -#include "rtmuller.h" +#include "muller.h" #include float rtmuller(float (*func)(float), float x1, float x2, float xacc) { diff --git a/hws/hw2/rtmuller.h b/hws/hw2/muller.h similarity index 100% rename from hws/hw2/rtmuller.h rename to hws/hw2/muller.h