無限不可能性ドライブ

『ニューラルネットワーク自作入門』に刺激されてExcelVBAでニューラルネットワークを作ってみたものの、やっぱり数学やらなきゃと思い少しずつやってきたのもあって、自分の知識の整理とかそういった感じです。

(お題)式を解析して導関数を求める

面白そうなお題があったので挑戦。


Option Explicit

Public Sub Main()
    Dim y As String
    Dim y2 As String
    Dim y_prime As String
    Dim prime As String
    Dim pos As Long
    Dim i As Long
    Dim char As String
    Dim buf As String
    
    y = "y = 5x^3 + 2x^2 + 7x + 5"
    y = Replace(y, " ", "")                 '空白除去(y=5x^3+2x^2+7x+5)
    
    pos = InStr(y, "=")
    y_prime = Left(y, pos)                  'y=
    y2 = Mid(y, pos + 1)                    '5x^3+2x^2+7x+5

    For i = 1 To Len(y2)
        char = Mid(y2, i, 1)
        If char = "+" Or char = "-" Then
            y_prime = y_prime & getPrime(buf) & char
            buf = ""
        Else
            buf = buf & char
        End If
    Next
    
    y_prime = y_prime & getPrime(buf)
    
    If Right(y_prime, 1) = "+" Or Right(y_prime, 1) = "-" Then
        y_prime = Left(y_prime, Len(y_prime) - 1)
    End If
    
    Debug.Print y_prime                 'y=15x^2+4x+7

End Sub

Private Function getPrime(ByRef aFormula As String) As String
    Dim pos As Long
    Dim x As String
    Dim exponent As Long
    
    pos = InStr(aFormula, "^")
    
    If pos > 0 Then
        x = Left(aFormula, pos - 1)
        exponent = Val(Mid(aFormula, pos + 1))
        getPrime = exponent * Val(x) & "x"
        If exponent > 2 Then
             getPrime = getPrime & "^" & (exponent - 1)
        End If
    Else
        If InStr(aFormula, "x") > 0 Then
            getPrime = Val(aFormula)
        Else
            getPrime = ""
        End If
    End If
    
End Function

ちゃんとテストしてないけどお題はクリアできたからいいかな。

f:id:celaeno42:20181212233850p:plain