Page 1 of 1

math.sin and math.cos error

Posted: Mon Dec 16, 2013 5:59 pm
by yegorf1
Hi, all I'm running love 0.8.0 and when I launched this:

Code: Select all

print('math.sin 0: ' .. math.sin(0))
print('math.sin 90: ' .. math.sin(math.pi / 2))
print('math.sin 180: ' .. math.sin(math.pi))
print('math.sin 270: ' .. math.sin(math.pi / 2 * 3))
print('math.cos 0: ' .. math.cos(0))
print('math.cos 90: ' .. math.cos(math.pi / 2))
print('math.cos 180: ' .. math.cos(math.pi))
print('math.cos 270: ' .. math.cos(math.pi / 2 * 3))
I see this:

Code: Select all

math.sin 0: 0
math.sin 90: 1
math.sin 180: 1.2246467991474e-16
math.sin 270: -1
math.cos 0: 1
math.cos 90: 6.1232339957368e-17
math.cos 180: -1
math.cos 270: -1.836970198721e-16
What's the error?
Thanks (:

Re: math.sin and math.cos error

Posted: Mon Dec 16, 2013 6:42 pm
by markgo

[]

Posted: Mon Dec 16, 2013 9:38 pm
by bekey
-snip-

Re: math.sin and math.cos error

Posted: Mon Dec 16, 2013 11:50 pm
by Robin
No, Lua trig functions work with radians.

Re: math.sin and math.cos error

Posted: Tue Dec 17, 2013 2:20 am
by XCaptain
shouldn't there be some conversion from radians to degrees too?
math.rad(degrees)
This will return x degrees in radians.
math.deg(radians)
This is just the opposite.

[]

Posted: Tue Dec 17, 2013 3:44 am
by bekey
-snip-

Re: math.sin and math.cos error

Posted: Tue Dec 17, 2013 7:45 am
by Plu
Short answer: rounding errors.

This: 1.2246467991474e-16
Is this: 0.00000000000000012246467991474

Which is 0 for all practical purposes.

I'm guessing (but I'm not sure) that even Lua will agree and say it equals zero if you compare with it. Otherwise, you'd have to use a bit of floating point comparisons (ie; sin(x) <= 0.0000001) or make an exact comparison against the input for the function before you calculate the sin value of it.

Re: math.sin and math.cos error

Posted: Tue Dec 17, 2013 11:34 am
by Robin
Plu wrote:I'm guessing (but I'm not sure) that even Lua will agree and say it equals zero if you compare with it.
Nope:

Code: Select all

> print(1.2246467991474e-16 == 0)
false
Floating point comparisons are finicky, and you usually want to compare them within an epsilon (basically, a very small value that is the margin of error you choose).