How can i make the php cos function return the correct value?

后端 未结 3 929
情深已故
情深已故 2021-01-19 01:50

I\'ve tried

$x = cos(deg2rad($angle));

but it returns 6.12323399574E-17 when the angle is 90 degrees instead of 0. I read that this is a fl

3条回答
  •  耶瑟儿~
    2021-01-19 02:47

    6.12323399574E-17 is an extremely small floating point number (17 zeros after the decimal point followed by a 6), almost indistinguishable from 0. If you are dealing with floating points (as any cosine function must), you can't avoid issues like this. If you need to compare a floating point number to zero, you must do it with error bars (i.e. is this number within a certain range of values around zero), not absolute comparison, even with simpler functions than cosine. If you just need to do some math with the result (add it, multiply it, whatever), it will behave almost exactly like zero so you won't need to worry.

提交回复
热议问题