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

matlab例程

开发平台:

Matlab

  1. //C10.cpp
  2. //Creat Clamped Cubic Spline
  3. #include <iostream.h>
  4. const int N=6;
  5. void CCS(double x[],double a[],double b[],double c[],double d[],double df0,double dfn,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. alpha[0]=2*(a[1]-a[0])/h[0]-3*df0;
  14. alpha[n-1]=3*dfn-3*(a[n-1]-a[n-2])/h[n-2];
  15. for(i=1;i<n-1;i++)
  16. {
  17. alpha[i]=3*(a[i+1]-a[i])/h[i]-3*(a[i]-a[i-1])/h[i-1];
  18. }
  19. //Now solve the linear system,using Court Factorazation
  20. l[0]=2*h[0];
  21. u[0]=0.5;
  22. z[0]=alpha[0]/l[0];
  23. for(i=1;i<n-1;i++)
  24. {
  25. l[i]=2*(x[i+1]-x[i-1])-h[i-1]*u[i-1];
  26. u[i]=h[i]/l[i];
  27. z[i]=(alpha[i]-h[i-1]*z[i-1])/l[i];
  28. }
  29. l[n-1]=h[n-2]*(2-u[n-2]);
  30. z[n-1]=(alpha[n-1]-h[n-2]*z[n-2])/l[n-1];
  31. c[n-1]=z[n-1];
  32. for(i=n-2;i>-1;i--)
  33. {
  34. c[i]=z[i]-u[i]*c[i+1];
  35. b[i]=(a[i+1]-a[i])/h[i]-h[i]*(c[i+1]+2*c[i])/3;
  36. d[i]=(c[i+1]-c[i])/(3*h[i]);
  37. }
  38. }
  39. void main()
  40. {
  41. double a[N]={4.0,2.5,1.5,0.5,-0.5,4.0},
  42. x[N]={0.0,1.0,3.5,5.0,7.5,10.0},
  43. c[N],d[N],b[N],
  44. xp=2.5,
  45. df0=2.5,dfn=1.4,
  46. s,ds,dds,is;
  47. int i;
  48.     //Compute b[N],c[N],d[N]
  49. CCS(x,a,b,c,d,df0,dfn,N);
  50.     //locate xp
  51. for(i=0;i<N-1;i++)
  52. {
  53. if (xp>x[i]&&xp<x[i+1])
  54. break;
  55. }
  56. 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]);
  57. ds=b[i]+2*c[i]*(xp-x[i])+3*d[i]*(xp-x[i])*(xp-x[i]);
  58. dds=2*c[i]+6*d[i]*(xp-x[i]);
  59. is=0;
  60. for (i=0;i<N-1;i++)
  61. {
  62. 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]);
  63. }
  64. cout<<"The cubic spline is:"<<endl;
  65. for(i=0;i<N-1;i++)
  66. {
  67. 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;
  68. }
  69. cout<<"S: "<<s<<endl;
  70. cout<<"dS: "<<ds<<endl;
  71. cout<<"ddS: "<<dds<<endl;
  72. cout<<"IS: "<<is<<endl;
  73. cin>>i;
  74. }
  75. //The cubic spline is:
  76. //From 0 to 1 :4+4.75*(x-x[i])+4.33994*(x-x[i])^2+1.18606*(x-x[i])^3
  77. //From 1 to 3.5 :2.5+-0.439232*(x-x[i])+0.0701166*(x-x[i])^2+-0.0217695*(x-x[i])^3
  78. //From 3.5 to 5 :1.5+-0.496827*(x-x[i])+-0.0931545*(x-x[i])^2+-0.0133812*(x-x[i])^3
  79. //From 5 to 7.5 :0.5+-0.866614*(x-x[i])+-0.15337*(x-x[i])^2+0.136006*(x-x[i])^3
  80. //From 7.5 to 10 :-0.5+0.916654*(x-x[i])+0.866677*(x-x[i])^2+-0.205335*(x-x[i])^3
  81. //在x=2.5处,S: 1.92544
  82. //dS: -0.375826
  83. //ddS: -0.0556922
  84. //IS: 17.912