用C找到根 [英] Finding roots with C
本文介绍了用C找到根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要帮助使用直接搜索方法和Newton-Raphson方法查找函数的根。我有每个方法的单独代码,但我不知道如何使用指针将它们组合成一个代码。我最终需要使用的功能是
f(x)= x ^ 3 - 0.2589x ^ 2 + 0.02262x - 0.001122 = 0
这是我的直接搜索方法代码。
I need help finding a root of a function using both the direct search method and then the Newton-Raphson method. I have individual codes for each method, but I don't know how to combine them into one code using a pointer. The function I ultimately need to use is
f(x)= x^3 - 0.2589x^2 + 0.02262x - 0.001122 = 0
Here is my direct search method code.
#include <stdio.h>
#include <math.h>
#define PI 3.14159265
double f(double x);
double direct(double a, double b, int n);
int main()
{
double x0 = 12.0, xn = 16.0;
int n = 400;
printf( "The root is %f\n", direct(x0, xn, n) );
return 0;
}
double f(double x)
{
double y;
y = 667.38/x * (1 - exp(-0.146843*x)) - 40.0;
return y;
}
double direct(double a, double b, int n)
{
int i;
double dx, x, f1, f2;
dx = (b - a) / n;
f1 = f(a);
for (i = 1; i <= n; i++) {
x = a + dx * i;
f2 = f(x);
if (f1 * f2 <= 0) break;
f1 = f2;
}
return x - dx/2;
}
Here is my Newton-Raphson method code.
#include <stdio.h>
#include <math.h>
#define EPS0 1.0e-12
double f(double x);
double fp(double x);
double newton_raphson(double x, double eps);
int main()
{
double xi = 0, eps = 1.0e-6;
printf( "The root is %f\n", newton_raphson(xi, eps) );
return 0;
}
double f(double x)
{
double y;
y = 1.5*x / pow((1+x*x), 2) - 0.65 * atan(1/x) + 0.65*x / (1+x*x);
return y;
}
double fp(double x)
{
double y;
y = (2.8 - 3.2*x*x) / pow((1+x*x), 3);
return y;
}
double newton_raphson(double x, double eps)
{
double x1, dx, fx, fpx;
do {
fx = f(x);
fpx = fp(x);
if (fabs(fpx) < EPS0)
{
printf( "Warning: slope --> 0 !!!\n");
break;
}
x1 = x - fx/fpx;
dx = x1 - x;
x = x1;
} while (fabs(dx) > eps || fabs(fx) > EPS0);
return x1;
}
[edit]已添加代码块 - OriginalGriff [/ edit]
[edit]Code block added - OriginalGriff[/edit]
推荐答案
你所要做的就是重命名一组函数(所以它们有唯一的名字 - 目前你有两个不同的函数叫做f
,例如,然后将代码包含在一个文件中。
我创建一个新的main
函数并重命名现有的对于初学者来说,然后从new调用旧main
函数。然后当它工作时,你可以开始修改代码更整洁。
但你究竟是什么意思用指针将它们组合成一个代码我不知道 - 你可能想暂时考虑一下并尝试解释它更好!:笑:
All you have to do is rename one set of functions (so they have unique names - at present you have two different functions calledf
for example, then include the code in one file.
I'd create a newmain
function and rename both the existing ones for starters, then call the "old"main
functions from the "new". Then when it works you can start modifying the code to be "tidier".
But exactly what the heck you mean by "combine them into one code using a pointer" I have no idea - you might want to think about that for a while and try and explain it better! :laugh:
这篇关于用C找到根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文