[ACM]Solve It

Solve It - 10341

Root :: Contest Volumes :: Volume CIII
Input: standard input
Output: standard output
Time Limit: 1 second
Memory Limit: 32 MB
Solve the equation:
p*e-x + q*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: p, q, r, s, t 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

解題思考: Bisection Method - 二分法
勘根定理
若函數f(x)在[a,b]上連續,且f(a)f (b) <0, 則至少存在一c∈(a,b) ,使得f (c) = 0.




/*
*2009.4.7 Revised
*UVa Online Judge
*Root :: Contest Volumes :: Volume CIII
*10341
*Solve It
*/

#include <iostream>
#include <cmath>

#define e 2.7182818285
#define error 0.0000000001 //margin of error

using namespace std;

double p, q, r, s, t, u; // Global Variables

double function( double x );
double bisectionMethod(double a, double b);

int main()
{

while( cin >> p >> q >> r >> s >> t >> u )
{
if( function(0) * function(1) > 0 )
cout << "No solution" << endl;

else
printf("%.4lf\n", bisectionMethod(0, 1));
}

return 0;
}

double function( double x )
{
return p * pow(e, -x) + q * sin(x) + r * cos(x)
+ s * tan(x) + t * pow(x, 2) + u;
}

double bisectionMethod(double a, double b)
{

if( function(a) == 0 )
return a;

if( function(b) == 0 )
return b;

double z = ( a + b ) / 2;

if( abs( a - b ) < error ) // | a - b | < 0.0000000001
return z;

else
{
if( function(a) * function(z) < 0 )
return bisectionMethod(a, z);

else
return bisectionMethod(z, b);
}
}


0 Response to "[ACM]Solve It"