zoukankan      html  css  js  c++  java
  • 【PAT】3-1 二分法求多项式单根

    二分法的步骤为:

     检查区间长度,如果小于给定阈值,则停止,输出区间中点(a+b)/2;否则

    如果f(a)f(b)<0,则计算中点的值f((a+b)/2);

    如果f((a+b)/2)正好为0,则(a+b)/2就是要求的根;否则

    如果f((a+b)/2)与f(a)同号,则说明根在区间[(a+b)/2, b],令a=(a+b)/2,重复循环;

    如果f((a+b)/2)与f(b)同号,则说明根在区间[a, (a+b)/2],令b=(a+b)/2,重复循环;

    #include <iostream>
    #include <algorithm>
    #include <cstdlib>
    #include <cstdio>
    #include <string>
    #include <cstring>
    #include <cmath>
    #include <ctime>
    #include <set>
    using namespace std;
    
    
    #define read() freopen("data.in", "r", stdin)
    #define write() freopen("data.out", "w", stdout)
    #define clr( a , x ) memset ( a , x , sizeof a )  
    #define cpy( a , x ) memcpy ( a , x , sizeof a ) 
    #define _max(a,b) ((a>b)?(a):(b))
    #define _min(a,b) ((a<b)?(a):(b))
    #define LL long long 
    const int maxNumber=10002;
    
    double a3,a2,a1,a0;
    double f(double x)
    {
    	double sum;
    	sum = pow(x,3)*a3+pow(x,2)*a2+a1*x+a0;
    	return sum;
    }
    int main()
    {
    	//read();
    	double a,b;
    	double mid;
    	cin>>a3>>a2>>a1>>a0>>a>>b;
    	while(b-a >= 0.001)//因为精度要求是两位,那就保证最后的解在小数点后第三位精确就行
    	{
    		mid = (a+b)/2;
    		if (f(mid) == 0)
    		{
    			break;
    		}else if (f(a)*f(mid) < 0)
    		{
    			b = mid;
    		}else
    		{
    			a = mid;
    		}
    	}
    	mid = (a+b)/2;
    	printf("%.2f
    ",mid );
        return 0;
       
    }
    

      

  • 相关阅读:
    129. Sum Root to Leaf Numbers
    113. Path Sum II
    114. Flatten Binary Tree to Linked List
    112. Path Sum
    100. Same Tree
    300. Longest Increasing Subsequence
    72. Edit Distance
    自定义js标签库
    JS 实现Table相同行的单元格自动合并示例代码
    mysql 高版本only_full_group_by 错误
  • 原文地址:https://www.cnblogs.com/acmsummer/p/4355993.html
Copyright © 2011-2022 走看看