write a C program using full Muller-Brent algorithm to find the roots
时间: 2023-05-22 16:03:05 浏览: 126
test_full.rar_BOX-MULLER_Box muller_Box-Muller方法_muller_中心极限定理
Sure, I can help you with that. Here is an example C program that uses the full Muller-Brent algorithm to find the roots:
```
#include <stdio.h>
#include <math.h>
double f(double x) {
return x * sin(x) - 1;
}
double muller_brent(double a, double b, double c, double tol) {
double fa = f(a);
double fb = f(b);
double fc = f(c);
double d, e, q, r, p;
double denom, eps, tol1, xm;
int iter = 0;
do {
denom = (b - a) * (c - b) * (c - a);
eps = 1e-20;
tol1 = tol * fabs(b) + eps;
xm = 0.5 * (a + b);
if (fabs(fc) < fabs(fb)) {
a = b; b = c; c = a;
fa = fb; fb = fc; fc = fa;
}
q = (a - xm) * (fb - fc);
r = (b - xm) * (fa - fc);
p = (b - a) * (fa - fc);
d = 2.0 * p - sign(p) * (q - r);
e = sign(b - a) * sign(fa - fb) * fabs(q - r);
if (fabs(denom) > eps) {
d /= denom;
e /= denom;
} else {
d = e = 0;
}
if (fabs(e) < tol1 || iter > 100) {
b += sign(b - a) * tol1;
return b;
}
if (fabs(d) < tol1) {
xm = b + sign(b - a) * tol1;
} else if (d > 0) {
xm = b - e / (d + sqrt(d * d - 4.0 * p * e));
} else {
xm = b - 2.0 * p / (d - sqrt(d * d - 4.0 * p * e));
}
if (isnan(xm) || isinf(xm)) {
xm = (a + b) / 2;
}
double fxm = f(xm);
a = b;
b = xm;
fa = fb;
fb = fxm;
iter++;
} while (iter <= 100);
return NAN;
}
int main() {
double root = muller_brent(0, 2.0, 4.0, 1e-9);
printf("root = %f\n", root);
return 0;
}
```
This program defines a function `f(x)` that takes a single input variable `x` and returns the value of the function `x * sin(x) - 1`. It then uses the Muller-Brent algorithm to find a root of this function in the interval `[0, 2.0, 4.0]` with a tolerance of `1e-9`. The `sign` function used in the algorithm is defined as:
```
double sign(double x) {
return (x >= 0.0) ? 1.0 : -1.0;
}
```
阅读全文