views:

62

answers:

1

Does anyone know of a Calculus library for JavaScript? I've done some Googling and haven't come up with anything. I applied for the WolframAlpha API, but that's expensive unless they choose to give me a grant.

Ideally, I could feed an Array of 2d points into a function, and get back the graph (Array) of points of the derivative.

If such a library does not exist, I will create one to share.

+2  A: 

Since you say you have a 2-D array of points, I assume you have a function of two variables f(x, y). That means you don't have a single derivative. Instead you get a set of partial derivatives.

You could approximate the partial derivatives using finite difference formulas.

The partial derivative with respect to x at f(x, y) would be (f(x+h, y) - f(x-h, y))/2h.

The partial derivative with respect to y at f(x, y) would be (f(x, y+h) - f(x, y-h))/2h.

In these formulas, h is the space between nodes on your grid, assuming you have a regularly spaced grid. If the horizontal and vertical spacings are different, use the horizontal spacing for the partial with respect to x and the vertical spacing for the partial with respect to y.

Update: I misunderstood your question. I thought the 2-D array was an array of domain values. If you have a list of x and f(x) values, you can approximate f'(x) as (f(x+h) - f(x-h)) / 2h. This will work everywhere except at the first and last points where one of the terms will be out of range. You can use (f(x + h) - f(x))/h at the left end and (f(x) - f(x-h))/h at the right end. The approximation will be less accurate at the end points but that can't be avoided.

John D. Cook
I think it's actually a function of one variable, f(x) = y. Each value of x is spaced by 1. Can I still use the finite difference formula?
Zachary Burt
Great! Is that still valid when 'h' is very large (1)?
Zachary Burt
The accuracy is going to depend on two things: h^2 and the size of the third derivative. If h = 1, your error will be large unless f'''(x) is small, i.e. unless f is approximately quadratic.
John D. Cook
It's hard to say what will work well enough without knowing more about your application. But one thing that people often do is fit a "natural cubic spline" to the data and then differentiate the spline *exactly*. It should be easy to find spline code if you search.
John D. Cook