[关闭]
@yang12138 2019-05-06T14:43:55.000000Z 字数 1367 阅读 886

一元n次函数求零点

未分类


给定,求满足


的全部

基础思路是求导后,求出导函数的零点,然后对每个单调区间进行二分求零点,导函数的零点通过递归求解。
注意有些零点是单调区间的端点,在导函数中这些零点应该去掉,但是在最终求解的函数中应该保留。

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4. const int N=20;
  5. const double eps=1e-9;
  6. const double INF=1e6;
  7. typedef vector<double> fun;
  8. int dcmp(double x){
  9. if(fabs(x)<eps) return 0;
  10. return x<0?-1:1;
  11. }
  12. fun cal_d(fun f,int n){
  13. fun ans(n,0.0);
  14. for(int i=0;i<n;i++){
  15. ans[i]=f[i+1]*(i+1);
  16. }
  17. return ans;
  18. }
  19. double val(double x,fun f,int n){
  20. double ans=f[n];
  21. for(int i=n-1;i>=0;i--){
  22. ans=ans*x+f[i];
  23. }
  24. return ans;
  25. }
  26. int search_ans(double l,double r,fun f,int n,double& ans){
  27. int ret=dcmp(val(l,f,n)*val(r,f,n));
  28. if(ret==0){
  29. if(dcmp(val(l,f,n))==0) ans=l;
  30. else ans=r;
  31. return 2;
  32. }
  33. else if(ret==1){
  34. return 0;
  35. }
  36. double a=l,b=r;
  37. while(l+eps<r){
  38. double mid=(l+r)/2;
  39. if(dcmp(val(mid,f,n)*val(l,f,n))>=0) l=mid;
  40. else r=mid;
  41. }
  42. ans=l;
  43. return 1;
  44. }
  45. fun cal_root(fun f,int n,bool flag=0){
  46. if(n==1) return fun(1,-f[0]/f[1]);
  47. fun dfun=cal_d(f,n);
  48. fun droot=cal_root(dfun,n-1);
  49. droot.insert(droot.begin(),-INF);
  50. droot.push_back(INF);
  51. fun ans;
  52. for(int i=1;i<(int)droot.size();i++){
  53. double x;
  54. int ret=search_ans(droot[i-1],droot[i],f,n,x);
  55. if(ret==0) continue;
  56. else if(ret==1) ans.push_back(x);
  57. else{
  58. if(flag) ans.push_back(x);
  59. }
  60. }
  61. return ans;
  62. }
  63. void solve(){
  64. int n;
  65. scanf("%d",&n);
  66. fun f(n+1,0.0);
  67. for(int i=n;i>=0;i--){
  68. scanf("%lf",&f[i]);
  69. }
  70. fun ans=cal_root(f,n,1);
  71. for(auto x:ans){
  72. printf("%.6f %.6f\n",x,val(x,f,n));
  73. }
  74. printf("\n");
  75. }
  76. int main(){
  77. solve();
  78. return 0;
  79. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注