c9.cpp
上传用户:zhdd911129
上传日期:2007-05-11
资源大小:722k
文件大小:2k
源码类别:

matlab例程

开发平台:

Matlab

  1. //C9.cpp
  2. //Creat Natuarl Cubic Spline
  3. #include <iostream.h>
  4. const int N=6;
  5. void NCS(double x[],double a[],double b[],double c[],double d[],int n)
  6. {
  7. double h[N-1],alpha[N-1],l[N],z[N],u[N];
  8. int i;
  9. for (i=0;i<n-1;i++)
  10. {
  11. h[i]=x[i+1]-x[i];
  12. }
  13. for(i=1;i<n-1;i++)
  14. {
  15. alpha[i]=3*(a[i+1]-a[i])/h[i]-3*(a[i]-a[i-1])/h[i-1];
  16. }
  17. //Now solve the linear system,using Court Factorazation
  18. l[0]=u[0]=z[0]=0;
  19. for(i=1;i<n-1;i++)
  20. {
  21. l[i]=2*(x[i+1]-x[i-1])-h[i-1]*u[i-1];
  22. u[i]=h[i]/l[i];
  23. z[i]=(alpha[i]-h[i-1]*z[i-1])/l[i];
  24. }
  25. l[n-1]=1;
  26. z[n-1]=c[n-1]=0;
  27. for(i=n-2;i>-1;i--)
  28. {
  29. c[i]=z[i]-u[i]*c[i+1];
  30. b[i]=(a[i+1]-a[i])/h[i]-h[i]*(c[i+1]+2*c[i])/3;
  31. d[i]=(c[i+1]-c[i])/(3*h[i]);
  32. }
  33. }
  34. void main()
  35. {
  36. double a[N]={4.0,2.5,1.5,0.5,-0.5,4.0},
  37. x[N]={0.0,1.0,3.5,5.0,7.5,10.0},
  38. c[N],d[N],b[N],
  39. xp=2.5,
  40. s,ds,dds,is;
  41. int i;
  42.     //Compute b[N],c[N],d[N]
  43. NCS(x,a,b,c,d,N);
  44.     //locate xp
  45. for(i=0;i<N-1;i++)
  46. {
  47. if (xp>x[i]&&xp<x[i+1])
  48. break;
  49. }
  50. s=a[i]+b[i]*(xp-x[i])+c[i]*(xp-x[i])*(xp-x[i])+d[i]*(xp-x[i])*(xp-x[i])*(xp-x[i]);
  51. ds=b[i]+2*c[i]*(xp-x[i])+3*d[i]*(xp-x[i])*(xp-x[i]);
  52. dds=2*c[i]+6*d[i]*(xp-x[i]);
  53. is=0;
  54. for (i=0;i<N-1;i++)
  55. {
  56. is+=a[i]*(x[i+1]-x[i])+b[i]/2*(x[i+1]-x[i])*(x[i+1]-x[i])+c[i]/3*(x[i+1]-x[i])*(x[i+1]-x[i])*(x[i+1]-x[i])+d[i]/4*(x[i+1]-x[i])*(x[i+1]-x[i])*(x[i+1]-x[i])*(x[i+1]-x[i]);
  57. }
  58. cout<<"The cubic spline is:"<<endl;
  59. for(i=0;i<N-1;i++)
  60. {
  61. cout<<"From "<<x[i]<<" to "<<x[i+1]<<" :"<<a[i]<<"+"<<b[i]<<"*(x-x[i])+"<<c[i]<<"*(x-x[i])^2+"<<d[i]<<"*(x-x[i])^3 "<<endl;
  62. }
  63. cout<<"S: "<<s<<endl;
  64. cout<<"dS: "<<ds<<endl;
  65. cout<<"ddS: "<<dds<<endl;
  66. cout<<"IS: "<<is<<endl;
  67. cin>>i;
  68. }
  69. //The cubic spline is:
  70. //From 0 to 1 :4+-1.68875*(x-x[i])+0*(x-x[i])^2+0.188746*(x-x[i])^3
  71. //From 1 to 3.5 :2.5+-1.12251*(x-x[i])+0.566237*(x-x[i])^2+-0.110893*(x-x[i])^3
  72. //From 3.5 to 5 :1.5+-0.370573*(x-x[i])+-0.265462*(x-x[i])^2+0.0453779*(x-x[i])^3
  73. //From 5 to 7.5 :0.5+-0.86066*(x-x[i])+-0.0612619*(x-x[i])^2+0.0982103*(x-x[i])^3
  74. //From 7.5 to 10 :-0.5+0.674474*(x-x[i])+0.675315*(x-x[i])^2+-0.0900421*(x-x[i])^3
  75. //在x=2.5处,S: 1.716
  76. //dS: -0.172328
  77. //ddS: 0.134434
  78. //IS: 12.0992