Sunday, May 24, 2009

Programming: sin and cos with floating point

so im having a really weird behavior recently: im trying to calculate a cos value in C++. Looks easy huh, well yes until I got this error: my angle is 90 so the cos value should be 0, but it wasn't. Instead of having 0, I got 0.000xxx which is when Im in the boundary of an vertical edge, its really significant since I cant move horizontal.

So I notice the problem was happened because I multiply my angle with PI_RADIAN. This is a must since cos function input a radian value. Instead of having half of the radian, I got 'almost' half of it. And when I use it in cos function, I did not give me 0. 

I haven't figure out how to handle this problem but first thing I want to do is to find out how to cut the decimal precision of float. I will update this post as soon as I got the solution.

Update: fortunately, I use lookup table for sin and cos value. Apparently the only way to handle this is to either convert to string and cut it (there's a smart way of doing this), or multiply by 10^(significant number) convert to int, and divide by the same 10 multiplication. Its quite too many ways for doing a real time calculation so try to trick it out. 

1 comment:

Ronsen said...

coba yah, yg dibahas yg lebih manusiawi. :))