| クラスモジュールの便利な使い方V | ||
|
|
||
| ここは、Uでの問題点を解決します。 Uでの問題点の、シンプソンのコードの引数が、特定のクラスのf( )という関数に制限されているという点があります。 引数のクラスを、変えてやれば、いろいろなクラスのf( )に、アクセスできるのですが、 シンプソンの引数も、いちいち変えたくないという方に、さらに、違う方法があります。 それは、引数を、以下のように、変えれば、一挙に解決できます。 |
||
|
|
||
| Function csinp(x1 As Double, x2 As Double, ff As Object) As Double Dim dd As Integer Dim i As Integer Dim dd2 As Integer Dim h As Double Dim an As Double Dim an1 As Double Dim y As Double Dim j As Integer Dim x As Double csinp = 0 If x1 = x2 Then Exit Function End If i = 2 dd2 = 2 h = (x2 - x1) / 2 an = ff.f(x1) + 4 * ff.f(x1 + h) + ff.f(x2) * h / 2 an1 = an * 0.9 Do While (Abs(an1 - an) / an * 100 > 0.0000001) an = an1 dd = dd2 * i h = (x2 - x1) / dd y = ff.f(x1) x = x1 For j = 1 To i x = x + h y = y + 4 * ff.f(x) x = x + h y = y + 2 * ff.f(x) Next j y = y - ff.f(x2) an1 = y * h / 3 i = i + 1 Loop csinp = an1 End Function |
||
|
|
||
| クラスsinp2のメッソドcsinpのコード 変わった所は、引数の所だけです。 引数の型をObjectにすると、どのクラスモジュールでもよく、 標準モジュールで、指定したクラスモジュールのf( )にアクセスできるようになります。 |
||
|
|
||
| クラスモジュールfun21 コード | ||
| Public Function f(x As Double) As Double f = x ^ 2 End Function |
||
|
|
||
| クラスモジュールfun22 コード | ||
| Public Function f(x As Double) As Double f = x ^ 3 End Function |
||
|
|
||
で、引数をObjectにしたcsinpは、コードを完全に変えることなく、 クラス fun21,fun22の式f( )の積分値を計算できるようになります。 標準モジュールのコードは以下の二つになります。 |
||
|
|
||
| Public Function sinp21(x1 As Double, x2 As Double) As Double Dim oa As New sinp2 Dim ob As New fun21 sinp21 = oa.csinp(x1, x2, ob) End Function |
||
|
|
||
| Public Function sinp22(x1 As Double, x2 As Double) As Double Dim oa As New sinp2 Dim ob As New fun22 sinp22 = oa.csinp(x1, x2, ob) End Function |
||
|
|
||
| 計算結果は、イミディエトウィドウで、簡単に計算できます。 以下に示します。 |
||
|
||
| 以上で、クラスモジュールの便利な使い方、T〜Vを、終わります。 応用して、いろいろ、便利なコードを開発してみてください。 |