Python float to int conversion

前端 未结 5 1033
南笙
南笙 2020-11-28 09:13

Basically, I\'m converting a float to an int, but I don\'t always have the expected value.

Here\'s the code I\'m executing:

x = 2.51

print(\"         


        
5条回答
  •  情话喂你
    2020-11-28 09:32

    int converts by truncation, as has been mentioned by others. This can result in the answer being one different than expected. One way around this is to check if the result is 'close enough' to an integer and adjust accordingly, otherwise the usual conversion. This is assuming you don't get too much roundoff and calculation error, which is a separate issue. For example:

    def toint(f):
        trunc = int(f)
        diff = f - trunc
    
        # trunc is one too low
        if abs(f - trunc - 1) < 0.00001:
            return trunc + 1
        # trunc is one too high
        if abs(f - trunc + 1) < 0.00001:
            return trunc - 1
        # trunc is the right value
        return trunc
    

    This function will adjust for off-by-one errors for near integers. The mpmath library does something similar for floating point numbers that are close to integers.

提交回复
热议问题