Cos(90) returning a value very close to 0, but I need 0?

后端 未结 5 895
旧时难觅i
旧时难觅i 2021-01-07 04:00

The values for temp_x_btm_left = 0 & temp_y_btm_left=1;

angle = 90;

//Moving the bottom left coordinates
_btm_left.real() = (temp_x_btm_left * cos(angle         


        
相关标签:
5条回答
  • 2021-01-07 04:08

    One solution would be to set up an Epsilon equal to some magical small value and then check whether the absolute value of your result provided by a function is less (or less-or-equal) to your Epsilon.

    (Naming it Epsilon is just a convention; it could be double MagicalNumberIndeed = VerySmallValue;)

    0 讨论(0)
  • 2021-01-07 04:13

    The "magical epsilon" referred to in previous answers is actually provided by the language via

     #include <limits>
     std::numeric_limits<float>::epsilon();
    

    and

     std::numeric_limits<double>::epsilon();
    

    which is "the difference between 1 and the least value greater than 1 that is representable"

    0 讨论(0)
  • 2021-01-07 04:14

    As long as |v1-v2| < predefinedDelta, simply consider v1 == v2.

    0 讨论(0)
  • 2021-01-07 04:25

    The trigonometric functions take an argument in radians, not in degree. Your calculation of angle*PI/180 doesn't yield exactly PI/2, which is of course not exactly representable as a floating point.

    A solution would be a comparison to special values before the conversion to radians, e. g.

    if (angle == 90.0)
        x = 0.0
    else
        x = cos(angle*PI/180.0)
    
    0 讨论(0)
  • 2021-01-07 04:31

    Pre-calculate your angle calculations, then use the results. Something like:

    if (angle == 90) {
      cos_angle = 0
    } else {
      cos_angle = cos(angle)
    }
    ...
    _btm_left.real() = ... * cos_angle ...
    

    This has the additional benefit of doing fewer calls to cos() and sin().

    Keep in mind that if angle is a float, doing something like angle == 90 could always return false, because of how floating point numbers are represented internally. You might want to change that to something like:

    if (abs(angle-90) < some_small_number) {
    
    0 讨论(0)
提交回复
热议问题