This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Exerro's profile picture

[solved] Math problems ( trigonometry )

Started by Exerro, 30 May 2013 - 03:30 AM
Exerro #1
Posted 30 May 2013 - 05:30 AM
Hi,
I have been going on a bit of a maths rampage, trying lots of new things to do with vectors but one thing has left me completely stumped.
I made a function that should give you the coordinates of a point that is [length] away from another point at [angle] degrees:

local angle = math.rad( angle )
local x2 = x + math.cos( angle ) * length
local y2 = y - math.sin( angle ) * length
return x2, y2
So this should work right?
For something like 45 deg it works but when I put in 180…It really doesn't, it returns -20, and 2.44….( the x, y is 0, 0 and length is 20 )
I have no idea why it does this and could really do with some help
Thanks
Pyro_ #2
Posted 30 May 2013 - 09:47 AM
Hey awsumben13,

So you are basically trying to convert from polar to Cartesian coordinates, your trigonometric math is correct, except for the fact that on line 3, you define y2 as y minus sin angle * length. If you change that to a plus you should be all good.

Pyro_
Bomb Bloke #3
Posted 30 May 2013 - 10:41 AM
y2 is actually being set to 2.4492936E-15. The "E-15" means that you need to move the decimal place fifteen places to the left to get the actual number (it's a way of abbreviating things); hence it's saying y2 = 0.0000000000000024492936.

The reason you get that result instead of what you're expecting (0) is because "angle" is being rounded. I'm not sure there's much you can do about that (you can ask it for math.sin(math.pi) and it'll still get it wrong), but you can take the edge off by rounding your results too; eg, if you want the nearest integers:

return ((x2>=0) and math.floor(x2+0.5) or math.ceil(x2-0.5)), ((y2>=0) and math.floor(y2+0.5) or math.ceil(y2-0.5))