求解方程(二分法)

 
//求一个一元二次方程的根

import java.util.*;
public class math{
         public static void main(String[] args){
           double a,b,c,x1,x2;
           double p;
           Scanner sc=new Scanner(System.in);
           a=sc.nextDouble();
           b=sc.nextDouble();
           c=sc.nextDouble();
           System.out.println(a+" "+b+" "+c);
           p=b*b-4*a*c;
           x1=(-b+Math.sqrt(p))/(2*a);
           x2=(-b-Math.sqrt(p))/(2*a);
           System.out.println(x1+" "+x2); 
         }
}
//求方程x的3次方-sqrt(x)-5=0;在闭区间[1,4]上的实数根.
import java.util.*;
public class math{
	public static void main(String[] args){
		double p=1e-15;
		double left,right,x1,x2;
		left=1.0;
		right=4.0;
		double mid=0.0;
		for(int i=1;i<=100;i++){
		    mid=(left+right)/2.0;
			if(Math.abs(mid*mid*mid-Math.sqrt(mid)-5.0)<=p) break;
			if(mid*mid*mid-Math.sqrt(mid)-5.0>0){
				right=mid;
			}
			else left=mid;
		}
		System.out.println(mid);
	}
}

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