Uva--10341(二分求线性方程解)

2014-07-23 20:42:12

Problem F

Solve It

Input: standard input

Output: standard output

Time Limit: 1 second

Memory Limit: 32 MB

Solve the equation:
        p*e-xq*sin(x) + r*cos(x) + s*tan(x) + t*x2 + u = 0
        where 0 <= x <= 1.

Input

Input consists of multiple test cases and terminated by an EOF. Each test case consists of 6 integers in a single line: pqrst and u (where 0 <= p,r <= 20 and -20 <= q,s,t <= 0). There will be maximum 2100 lines in the input file.

Output

For each set of input, there should be a line containing the value of x, correct upto 4 decimal places, or the string "No solution", whichever is applicable.

Sample Input

0 0 0 0 -2 1
1 0 0 0 -1 2
1 -1 1 -1 -1 1

Sample Output

0.7071
No solution
0.7554

思路:经典的用二分求线性方程解,唯一的坑点在于精度!QAQ 竟然让我开到了1e-12

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <cstdlib>
 4 #include <cmath>
 5 #include <iostream>
 6 #include <algorithm>
 7 using namespace std;
 8 const double eps = 1e-12;
 9 
10 double p,q,r,s,t,u;
11 
12 double Cal(double x){
13     return (p * exp(-x) + q * sin(x) + r * cos(x) + s * tan(x) + t * x * x + u);
14 }
15 int main(){
16     while(scanf("%lf%lf%lf%lf%lf%lf",&p,&q,&r,&s,&t,&u) == 6){
17         double l = 0,r = 1;
18         int Judge = 0;
19         if(fabs(Cal(l)) < eps){
20             printf("%.4lf\n",l);
21             Judge = 1;
22         }
23         else if(fabs(Cal(l)) < eps){
24             printf("%.4lf\n",r);
25             Judge = 1;
26         }
27         else{
28             while(r - l > 0.0){
29                 double mid = (l + r) / 2;
30                 double ans = Cal(mid);
31                 //printf("%.4lf\n",ans);
32                 if(fabs(ans) <= eps){
33                     printf("%.4lf\n",mid);
34                     Judge = 1;
35                     break;
36                 }
37                 else if(ans > 0)
38                     l = mid;
39                 else
40                     r = mid;
41             }
42         }
43         if(!Judge)
44             printf("No solution\n");
45     }
46     return 0;
47 }
posted @ 2014-07-23 20:43  Naturain  阅读(137)  评论(0编辑  收藏  举报