作业:二分法求方程的根

用二分法+递归解一元高次方程。此方法只能求出在规定范围内的一个根,并求出原函数在该解处的值。

附上原题:

题目描述
Joy is a twelfth grade student who is aiming to go to SUSTech. One day, when he is doing math practices. He found a problem very hard. It gives a function goes like F(x) = 5x7+6x6+3x3+4x2-2xy (0 <= x <=100), y is a given real number. Can you help Joy find the minimum value of F(x) when x is in its domain?

输入
The first line of the input contains an integer T (1 <= T <= 100) which means the number of test cases. Then T lines follow, each line has only one real numbers Y (0 < Y < 1010).

输出
For each case, print the case number as well as the minimum value (accurate up to 4 decimal places) in one line, when x is in its domain.
样例输入
3
100
200
300
样例输出
Case 1: -193.3774
Case 2: -448.1475
Case 3: -729.3383

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
    static double F(double x,double y) {
        return 5*Math.pow(x, 7)+6*Math.pow(x, 6)+3*Math.pow(x, 3)+4*x*x-2*x*y;
        //原方程
    }
    static double f(double x,double y) {
        return 35*Math.pow(x, 6)+36*Math.pow(x, 5)+9*x*x+8*x-2*y;
        //原方程的一阶导
    }
    static double solve(double y,double left,double right) {
        double mid=(right+left)/2;
        if(f(right,y)-f(left,y)<0.0001) {
            return (right+left)/2;
        }
        else if(f(mid,y)>0) {
            right=mid;
            return solve(y, left, right);
        }
        else {
            left=mid;
            return solve(y, left, right);
        }
    }
    //用递归和二分法求一阶导零点
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        int n= Integer.parseInt(input.readLine());
        for(int i=0;idouble y=Double.parseDouble(input.readLine());
            double x=solve(y,0,100);
            System.out.println("Case "+(i+1)+":"+" "+String.format("%.4f", F(x,y)));
        }
    }
}

你可能感兴趣的:(作业:二分法求方程的根)