IT

round ()가 반올림되지 않는 것

lottoking 2020. 7. 23. 07:59
반응형

round ()가 반올림되지 않는 것


round () 함수에 대한 설명서 에는 숫자를 전달하고 소수점 이하 자릿수를 지나는 위치를 지정합니다. 따라서 다음 수행해야합니다.

n = 5.59
round(n, 1) # 5.6

그러나 실제로 오래된 오래된 부동 소수점 이상이 발생하고 다음을 얻습니다.

5.5999999999999996

UI의 목적을 위해을 표시해야합니다 5.6. 나는 인터넷을 찔 렀고 그것이 구현했다는 것과 같은 문서발견했다 . 불행히도이 내 Windows dev 시스템과 내가 시도한 각 Linux 서버에서 발생합니다. 여기도 참조하십시오 .

내 자신의 라운드를 만드는 데 부족한 점이 라이브러리?


저장 방법을 도울 수 없지만 최소한의 형식이 작동합니다.

'%.1f' % round(n, 1) # Gives you '5.6'

반올림하지 않으면 서식이 작동합니다.

"%.1f" % n

십진수 모듈을 사용하는 경우 '라운드'기능을 사용하지 않습니다. 다음은 기획 응용 프로그램을 사용할 때 반올림에 행사 것입니다.

Decimal(str(16.2)).quantize(Decimal('.01'), rounding=ROUND_UP)

16.20의 10 진수를 반환합니다.


round(5.59, 1)잘 작동합니다. 문제는 5.6을 이진 부동 소수점으로 정확하게 표현할 수 있습니다.

>>> 5.6
5.5999999999999996
>>> 

Vinko가 말했듯이 세련된 형식을 사용하여 반올림하여 표시 할 수 있습니다.

에는 파이썬 필요한 경우 십진 산술 모듈 이 있습니다.


str(round(n, 1))대신 '5.6'을 얻 습니다 round(n, 1).


데이터 유형을 정수로 전환 할 수 있습니다.

>>> n = 5.59
>>> int(n * 10) / 10.0
5.5
>>> int(n * 10 + 0.5)
56

그런 다음 로케일의 숫자 구분 기호를 삽입하여 숫자를 표시하십시오.

그러나 Jimmy의 대답 이 더 좋습니다.


부동 소수점 수학은 경미하지만 성 가시고 정밀한 부정확성에 취약합니다. 정수 또는 고정 소수점으로 작업 할 수 있으면 준비가 보장됩니다.


소수점을 모듈 살펴보십시오

십진수는 "사람을 염두에두고 가장 부동 소수점 모델을 기반으로하며 반드시 있어야하며 원칙을 가지고 있습니다. 컴퓨터는 사람들이 학교에서 배우는 산술과 같은 방식으로 작동하는 산술을 제공해야합니다." – 십진 산술 스펙에서 발췌.

십진수는 표현 될 수 있습니다. 1.1 및 2.2와 같은 숫자는 이진 부동 소수점으로 정확하게 표현되지 않았습니다. 최종 사용자는 일반적으로 이진 부동 소수점과 마침 1.1 + 2.2가 3.3000000000000003으로 표시됩니다.

진수 부동 소수점 연산을 필요로 쓰기 응용 프로그램에 쉽게 그것을 만드는 작업의 종류를 제공합니다. 또한 , 회계, 사람이 읽을 수있는 형식으로 예를 그 결과를 제시해야합니다.


실제로 큰 문제입니다. 이 코드를 사용 :

print "%.2f" % (round((2*4.4+3*5.6+3*4.4)/8,2),)

4.85를 표시합니다. 그런 다음

print "Media = %.1f" % (round((2*4.4+3*5.6+3*4.4)/8,1),)

4.8을 보여줍니다. 직접 계산하면 답은 4.85이지만 시도하면 다음과 있습니다.

print "Media = %.20f" % (round((2*4.4+3*5.6+3*4.4)/8,20),)

당신은 진실을 볼 수 있습니다 : 부동 소수점은 분모가 2의 거듭 제곱 인 가장 가까운 유한 분수의 합으로 저장됩니다.


%sprintf와 다른 언어 형식 연산자를 사용할 수 있습니다 .

mystring = "%.2f" % 5.5999

빨판을 printf .

print '%.1f' % 5.59  # returns 5.6

완벽한 작품

format(5.59, '.1f') # to display
float(format(5.59, '.1f')) #to round

내가 뭐하는 거지 :

int(round( x , 0))

이 경우 먼저 단위 레벨에서 반올림 한 다음 플로트 인쇄를 피하기 위해 정수로 변환합니다.

그래서

>>> int(round(5.59,0))
6

나는이 대답이 문자열 형식을 지정하는 것보다 더 잘 작동한다고 생각하며 round 함수를 사용하는 것이 더 감각적입니다.


암호:

x1 = 5.63
x2 = 5.65
print(float('%.2f' % round(x1,1)))  # gives you '5.6'
print(float('%.2f' % round(x2,1)))  # gives you '5.7'

산출:

5.6
5.7

여기에서 라운드 실패를 볼 수 있습니다. 이 두 숫자를 소수점 첫째 자리로 반올림하려면 어떻게해야합니까? 23.45 23.55 내 교육은이 값을 반올림하여 다음을 얻어야한다는 것입니다. 23.4 23.6 "규칙"은 이전 숫자가 홀수이면 반올림해야하고 이전 숫자가 짝수이면 반올림하지 않아야한다는 것입니다. 파이썬의 round 함수는 단순히 5를 자릅니다.


문제는 마지막 숫자가 5 일 때만 발생합니다. 예. 0.045는 내부적으로 0.044999999999999로 저장됩니다 ... 마지막 숫자를 6으로 늘리고 반올림 할 수 있습니다. 이렇게하면 원하는 결과를 얻을 수 있습니다.

import re


def custom_round(num, precision=0):
    # Get the type of given number
    type_num = type(num)
    # If the given type is not a valid number type, raise TypeError
    if type_num not in [int, float, Decimal]:
        raise TypeError("type {} doesn't define __round__ method".format(type_num.__name__))
    # If passed number is int, there is no rounding off.
    if type_num == int:
        return num
    # Convert number to string.
    str_num = str(num).lower()
    # We will remove negative context from the number and add it back in the end
    negative_number = False
    if num < 0:
        negative_number = True
        str_num = str_num[1:]
    # If number is in format 1e-12 or 2e+13, we have to convert it to
    # to a string in standard decimal notation.
    if 'e-' in str_num:
        # For 1.23e-7, e_power = 7
        e_power = int(re.findall('e-[0-9]+', str_num)[0][2:])
        # For 1.23e-7, number = 123
        number = ''.join(str_num.split('e-')[0].split('.'))
        zeros = ''
        # Number of zeros = e_power - 1 = 6
        for i in range(e_power - 1):
            zeros = zeros + '0'
        # Scientific notation 1.23e-7 in regular decimal = 0.000000123
        str_num = '0.' + zeros + number
    if 'e+' in str_num:
        # For 1.23e+7, e_power = 7
        e_power = int(re.findall('e\+[0-9]+', str_num)[0][2:])
        # For 1.23e+7, number_characteristic = 1
        # characteristic is number left of decimal point.
        number_characteristic = str_num.split('e+')[0].split('.')[0]
        # For 1.23e+7, number_mantissa = 23
        # mantissa is number right of decimal point.
        number_mantissa = str_num.split('e+')[0].split('.')[1]
        # For 1.23e+7, number = 123
        number = number_characteristic + number_mantissa
        zeros = ''
        # Eg: for this condition = 1.23e+7
        if e_power >= len(number_mantissa):
            # Number of zeros = e_power - mantissa length = 5
            for i in range(e_power - len(number_mantissa)):
                zeros = zeros + '0'
            # Scientific notation 1.23e+7 in regular decimal = 12300000.0
            str_num = number + zeros + '.0'
        # Eg: for this condition = 1.23e+1
        if e_power < len(number_mantissa):
            # In this case, we only need to shift the decimal e_power digits to the right
            # So we just copy the digits from mantissa to characteristic and then remove
            # them from mantissa.
            for i in range(e_power):
                number_characteristic = number_characteristic + number_mantissa[i]
            number_mantissa = number_mantissa[i:]
            # Scientific notation 1.23e+1 in regular decimal = 12.3
            str_num = number_characteristic + '.' + number_mantissa
    # characteristic is number left of decimal point.
    characteristic_part = str_num.split('.')[0]
    # mantissa is number right of decimal point.
    mantissa_part = str_num.split('.')[1]
    # If number is supposed to be rounded to whole number,
    # check first decimal digit. If more than 5, return
    # characteristic + 1 else return characteristic
    if precision == 0:
        if mantissa_part and int(mantissa_part[0]) >= 5:
            return type_num(int(characteristic_part) + 1)
        return type_num(characteristic_part)
    # Get the precision of the given number.
    num_precision = len(mantissa_part)
    # Rounding off is done only if number precision is
    # greater than requested precision
    if num_precision <= precision:
        return num
    # Replace the last '5' with 6 so that rounding off returns desired results
    if str_num[-1] == '5':
        str_num = re.sub('5$', '6', str_num)
    result = round(type_num(str_num), precision)
    # If the number was negative, add negative context back
    if negative_number:
        result = result * -1
    return result

이건 어떤가요:

round(n,1)+epsilon

참고 URL : https://stackoverflow.com/questions/56820/round-doesnt-seem-to-be-rounding-properly

반응형