計算機プログラムの構造と解釈(SICP)学習メモ
蒋 いつ峰 2008/08/30   |  プログラミング基礎
第一章 練習1.40~1.46 2008/08/30  |  PK:SICP 練習 1.40~1.46

SICP練習1.40~1.46です。プロシージャを返却値にする。


問題

練習1.40:newtons-method で x^3 + ax^2 + bx + c の零点を求める。
練習1.41:(((double (double double)) inc) 5) の返却値を求める。
練習1.42:複合関数を定義する。
練習1.43:関数の複数適用。
練習1.44:平滑化(smoothing)  → 略
練習1.45:n 乗根を求める  → 略
練習1.46:反復改良法  → 略


解答

練習1.40の解答

 
  1. float delegate(float) deriv(float delegate(float) g) {  
  2.     float dg(float x) {  
  3.         return (g(x + DX) - g(x)) / DX;  
  4.     }  
  5.     return &dg;  
  6. }  
  7.   
  8. float delegate(float) newton_transform(float delegate(float) g) {  
  9.     float dg(float x) {  
  10.         return x - g(x) / deriv(g)(x);  
  11.     }  
  12.     return &dg;  
  13. }  
  14.   
  15. float newtons_method(float delegate(float) g, float guess) {  
  16.     return fixedPoint(newton_transform(g), guess);  
  17. }  
  18.   
  19. /** 
  20.  * 練習1.40。 
  21.  * newtons-method で x^3 + ax^2 + bx + c の零点を求める。 
  22.  */  
  23. float cubic(float a, float b, float c) {  
  24.     float g(float x) {  
  25.         return x * x * x + a * x * x + b * x + c;  
  26.     }  
  27.     float root = newtons_method(&g, 1);  
  28.     return root;  
  29. }  

コンパイルは通りましたが、実行時 Stack Overflow エラーが発生していました。ロジックの問題か、D言語の問題か今のところ不明です。分かっている方は教えてください。

練習1.41の解答

(double (double double)) = (2 * 2) * (2 * 2) = 16回、ですから、解は inc を16回適用することです。結果は 16 + 5 = 21 でしょう。

練習1.42の解答

 
  1. /** 
  2.  * 練習1.42。 
  3.  * 複合関数を定義する。 
  4.  */  
  5. int compose(int delegate(int) f, int delegate(int) g, int x) {  
  6.     return f(g(x));  
  7. }  

実行結果。

c:\home\sicp>q1_40_q1_46.exe
---- 1.42 ----
compose(square, inc, 6) = 49


練習1.43の解答

 
  1. /** 
  2.  * 練習1.43。 
  3.  * 関数の重複適用。 
  4.  */  
  5. int repeated(int delegate(int) f, int x, int n) {  
  6.     int result = x;  
  7.     for(int i = 0; i < n; i++) {  
  8.         result = f(result);  
  9.     }  
  10.     return result;  
  11. }  

実行結果。

---- 1.43 ----
repeated(square, 5, 2) = 625

 


閲覧  |  コメント  |  目次

 
ヘルプ  |  ご利用規約  |  相互リンク  |  問合せ
リンクはご自由に、問合せはお気軽に
©2007 Uprush