Jump to content




[solved] Math problems ( trigonometry )


  • You cannot reply to this topic
2 replies to this topic

#1 Exerro

  • Members
  • 801 posts

Posted 30 May 2013 - 04: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

#2 Pyro_

  • Members
  • 39 posts
  • LocationAustralia

Posted 30 May 2013 - 08: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_

#3 Bomb Bloke

    Hobbyist Coder

  • Moderators
  • 7,099 posts
  • LocationTasmania (AU)

Posted 30 May 2013 - 09: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))






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users