Problem:
The equation f (x) = x^3+10x-20 is given, and the root of the equation at (a) is not less than the accuracy of 10^-4
Seems to be very simple a small problem, in fact, there is a lot of detail worth noting, first give the code
Method One:
#include <stdio.h>#include<math.h>DoubleFDoublex) { returnx*x*x+Ten*x- -;}intMain () {DoubleL,r,mid,ans; L=1; R=2; while(1) {Mid= (l+r)/2; DoubleCNT =f (mid); if(Fabs (CNT) <=0.0001) {ans=mid; printf ("%lf\n", CNT); Break; } if(CNT >0) R =mid; ElseL =mid; } printf ("%.4lf\n", ans); return 0;}
Method Two:
#include <stdio.h>#include<math.h>Doubleans;DoubleFDoublex) { returnx*x*x+Ten*x- -;}voidMDoubleLDoubleR) { DoubleMid = (l+r)/2; DoubleCNT =f (mid); if(Fabs (CNT) <= 1e-4) {ans=mid; return ; } if(CNT >0) m (l,mid); Elsem (mid,r);}intMain () {m (1,2); printf ("%.4lf\n", ans); return 0;}
The two methods do not differ in nature, the algorithm is essentially the same, but in the program implementation means slightly different, the method of a use of the loop, and method two recursion.
There are so few points to note
(1) How to determine the accuracy of less than 1e-4?
First we have to understand that we have to determine the precision of "root", that is, the value of the ANS of the F (ANS) =0 is not less than 1e-4, we do not know what the value of the truth is, but we can confirm his function value, that is, 0, So this problem translates into the value that we can calculate ans the value of the function f (ans) and 0 of the absolute difference is not greater than 1e-4, so we could find the current mid is the possible midpoint of the value, see if he and 0 is less than or equal to 1e-4, if it is, This mid is the result of our final request.
(2) For the determination of the values of the L and R for each iteration, there is no general rule for the time being, but in this problem, we can use the image to express the change law of L and R very intuitively.
First it is easy to find out that f (x) is monotonically incrementing on the definition field, then the value of x=1 is negative, and the value in x=2 is positive, then there must be only one root between them, so if the current calculated f (ANS) value is positive and negative, according to the figure, We all can clearly see who should be assigned to the value.
Calculation Method--C-language dichotomy method to find root