That's what he said.

Trig Function Gotchas in PHP, JavaScript and Excel

Fri, 04/13/2012 - 08:13 -- Doug

Physics. Mmmmhmm, fun!  No really. I had no idea that I could be so entertained with a calculator, a few free hours and a dry erase board. Having solved hundreds of problems over the last several weeks, I'd  write a few small physics simulations in JavaScript for the HTML5 canvas.

I started with a function to plot the course of a projectile fired at a given angle and velocity using: 

$$ s = v_{0}t+\frac{1}{2}at^2 $$

It should have been easy enough, but I just couldn't get the curve to look right. So I tried it by hand with a calculator and paper. Great. Next, I tried it in Excel. That looked good, too. Until I changed the angle from 45 to 30 and the ball looked like it had been thrown backwards and underground.

I checked my Excel function again, and it looked right: $ \sin(45^{\circ}) $.  Except that i was getting 0.8509 for the answer. D'oh! Radians. PHP, JavaScript, Excel...everything is expecting radians for the input. Why? I'm not really sure, but if you're working with degrees for the input, you're going to want to convert your angle to radians first, and then run your function.