Calculus#
Problem: Calculate derivative and integral of a curve, given the vectors x
and y
.
Test data:
⎕IO←0
x←0.25×⍳100
f←⍟1+x ⋄ g←10-⍨(x*0.5)+x÷2 ⋄ h←10×1○x÷5
]plot (f g h h)x
Derivative#
The derivative will be calculated as a simple ratio of the difference between two consequtive values. The differences will be calculated using the n-wise reduction operator (dyadic /
).
dy←2-/f ⋄ dx←2-/x ⋄ d←dy÷dx
]plot d x
We better define a function:
D←÷⍥(2-/⊢)
]plot ((f D x)(g D x)(h D x)) x
Noise#
The problem of calculating the derivative is more complicated if the function is not smooth. For example:
n←f+0.1-⍨0.2×?0⍴⍨≢f
]plot (n (n D x)) x
In such a case, it would be convenient to first perform some smoothing of the function, for example calculating a running average:
ns xs←10(+/÷⊣)¨n x
]plot (ns (ns D xs)) xs
Or defining a smoothing function:
S←(+/÷⊣)¨
]plot 10 D/⍤S n x
Integral#
To calculate the value of the integral we need to add, each step, the increment of the x value multiplied by the current value of the function at that point. Several options can be used to estimate the value of the function (previous point, next point, average, …). Here, the average of the value at the previous and next point is used.
∆x←¯2-/x ⋄ y←2(+/÷⊣)f ⋄ i←+\∆x×y
]plot i x
Again, we define a function to facilitate calculating the integral for any curve:
I←+\(¯2-/⊢)×2(+/÷⊣)⊣
]plot ((f I x)(g I x)(h I x))x
If we are only interested in the total value of the integral, we simply take the last value:
⊢/¨(f I x)(g I x)(h I x)
58.89219624 ¯12.29837376 38.22296274
Notice that no special action is needed to calculate the integral of noisy functions, although using a smoothed function is also possible:
]plot ((n I x)(0,⊃10 I/⍤S n x)) x