uva 10341

uva 10341 Solve It

链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1282

题意:求所给的方程的根

思路:对给定的方程求导,可得其在区间[0, 1] 为单调函数,故在区间[0, 1] 最多只有一个解。当 f(0)*f(1) > 0 时, 无解。

  有解情况时,根据离散牛顿迭代法求方程的根。 离散牛顿法(割线法)公式如下:

xk+1 = xk - f(x) / (f(xk)-f(xk-1))  * (xk - xk-1)

代码:

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <cmath>
 5 using namespace std;
 6 const double eps = 1e-9;
 7 inline int sig(double x){ return (x>eps) - (x<-eps); }
 8 
 9 int p, q, r, s, t, u;
10 double x;
11 inline double f(double x)
12 {
13     return p*exp(-x) + q*sin(x) + r*cos(x) + s*tan(x) + t*x*x + u;
14 }
15 
16 void solve()
17 {
18     double x1 = f(0.0), x2 = f(1.0);
19     if(x1 * x2 > 0)
20     {
21         puts("No solution");
22         return ;
23     }
24     x = 0.5, x1 = x2 = 0.0;
25     while(sig(x-x2))
26     {
27         x2 = x;
28         x = x - (f(x)*(x-x1)/(f(x)-f(x1)));
29         x1 = x2;
30     }
31     printf("%.4lf
", x);
32     return ;
33 }
34 
35 int main()
36 {
37     //freopen("in.txt", "r", stdin);
38     while(scanf("%d %d %d %d %d %d", &p, &q, &r, &s, &t, &u) != EOF)
39         solve();
40     return 0;
41 }

原文地址:https://www.cnblogs.com/Duahanlang/p/3382292.html