So I was doing a coding exercise (in Scratch) for fun and decided to try to create a piece of code that would be able to calculate the area of a function f(x)=x y (where y is some constant) of the form ∫ab f(x) dx, which I thought that I might be able to do.
The attempt I made on this started off with knowing that I had code that would help with this:
[scratchblocks]
define pow(base)(power)
set [result v] to [1]
set [base v] to (base)
set [power v] to (round (power))
set [done v] to [0]
if <(power) < [0]> then
set [base v] to [((1) / (base))]
set [power v] to [-1(() *(round (power))]
end
repeat until <[done v] = [1]>
if <(([power v]) mod (2)) = [0]> then
set [result v] to (([result v]) * ([base v]))
change [power v] by (-1)
end
if <(([power v]) mod (2)) > [0]> then
set [done v] to [1]
end
if <<not <<[done v] = [1]>>>
set [base v] to (([base v]) * ([base v]))
set [power v] to (([power v]) / (2))
end
end
[/scratchblocks]
I also had to create some new code to actually evaluate the integral, but it wasn't that difficult:
[scratchblocks]
define area from x to y of the form a^zda(x)(y)(z)
set [x v] to (x)
set [y v] to (y)
set [z v] to (z)
pow (x) ((z)+(1))
set [re2 v] to (result)
pow (y) ((z)+(1))
set [re3 v] to (result)
set [re4 v] to (((re3)-(re2))/(3))
[/scratchblocks]
Now, to test, I did ∫34 a 2da, which should get us (4^3)/3-9=64/3-9=21+(1/3)-9=12+(1/3)≈12.333
which it seems to have done.
Is this a reliable way of calculating the area from a point to a second point of an integral of the form ∫a b x^adx Scratch, or what could I do to make it more reliably do so?
You can just create a new function to integrate the mathematical function, plug in the limits, and then just calculate it!