How to alter a float by its smallest increment (or close to it)?

前端 未结 7 1196
余生分开走
余生分开走 2020-11-30 02:05

I have a double value f and would like a way to nudge it very slightly larger (or smaller) to get a new value that will be as close as possible to

7条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 02:50

    I found this code a while back, maybe it will help you determine the smallest you can push it up by then just increment it by that value. Unfortunately i can't remember the reference for this code:

    #include 
    
    int main()
    {
        /* two numbers to work with */
        double number1, number2;    // result of calculation
        double result;
        int counter;        // loop counter and accuracy check
    
        number1 = 1.0;
        number2 = 1.0;
        counter = 0;
    
        while (number1 + number2 != number1) {
            ++counter;
            number2 = number2 / 10;
        }
        printf("%2d digits accuracy in calculations\n", counter);
    
        number2 = 1.0;
        counter = 0;
    
        while (1) {
            result = number1 + number2;
            if (result == number1)
                break;
            ++counter;
            number2 = number2 / 10.0;
        }
    
        printf("%2d digits accuracy in storage\n", counter );
    
        return (0);
    }
    

提交回复
热议问题