산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> python

예제가 있는 Python round() 함수

둥근()

Round()는 파이썬에서 사용할 수 있는 내장 함수입니다. 입력으로 제공된 소수점 이하 자릿수로 반올림되는 부동 소수점 수를 반환합니다.

반올림할 소수점 이하 자릿수를 지정하지 않으면 0으로 간주하여 가장 가까운 정수로 반올림합니다.

이 Python 자습서에서는 다음을 배우게 됩니다.

구문:

round(float_num, num_of_decimals)

매개변수

설명

round() 메서드는 두 개의 인수를 취합니다.

두 번째 인수는 선택 사항이며 지정되지 않은 경우 기본값은 0이며 이 경우 가장 가까운 정수로 반올림되며 반환 유형도 정수가 됩니다.

소수점 이하 자릿수, 즉 두 번째 인수가 있으면 지정된 자릿수로 반올림됩니다. 반환 유형은 float입니다.

소수점 이하의 숫자가 주어진 경우

반환 값

num_of_decimals가 주어지지 않으면 정수 값을 반환하고 num_of_decimals가 주어지면 부동 소수점 값을 반환합니다. 소수점 이하 값이>=5이면 값은 +1로 반올림됩니다. 그렇지 않으면 언급된 소수점 이하 자릿수까지 값을 반환합니다.

반올림이 얼마나 많은 영향을 미칠 수 있습니까? (반올림 대 잘림)

반올림의 영향을 보여주는 가장 좋은 예는 증권 거래소 시장입니다. 과거, 즉 1982년에 Vancouver Stock Exchange(VSE):각 거래에서 주식 가치를 소수점 이하 세 자리까지 줄이는 데 사용되었습니다.

매일 거의 3000번 정도 했다. 누적된 잘림으로 인해 매월 약 25포인트가 손실됩니다.

값 자르기 대 반올림의 예가 아래에 나와 있습니다.

아래에 생성된 부동 소수점 숫자를 주식 값으로 고려하십시오. 지금은 다음 범위에 대해 생성하고 있습니다.

0.01과 0.05 사이의 1,000,000초.

예:

arr = [random.uniform(0.01, 0.05) for _ in range(1000000)]

반올림의 영향을 보여주기 위해 처음에는 소수점 3자리까지만 숫자를 사용해야 하는 작은 코드를 작성했습니다. 즉, 소수점 3자리 이하의 숫자는 잘립니다.

원래 합계 값, 잘린 값의 합계 및 원래 값과 잘린 값의 차이가 있습니다.

같은 숫자 집합에서 저는 round() 메서드를 소수점 3자리까지 사용하고 원래 값과 반올림된 값의 합계와 차이를 계산했습니다.

다음은 예제와 출력입니다.

예시 1

import random

def truncate(num):
    return int(num * 1000) / 1000

arr = [random.uniform(0.01, 0.05) for _ in range(1000000)]
sum_num = 0
sum_truncate = 0
for i in arr:
    sum_num = sum_num + i        
    sum_truncate = truncate(sum_truncate + i)
    
print("Testing by using truncating upto 3 decimal places")
print("The original sum is = ", sum_num)
print("The total using truncate = ", sum_truncate)
print("The difference from original - truncate = ", sum_num - sum_truncate)

print("\n\n")
print("Testing by using round() upto 3 decimal places")
sum_num1 = 0
sum_truncate1 = 0
for i in arr:
    sum_num1 = sum_num1 + i        
    sum_truncate1 = round(sum_truncate1 + i, 3)


print("The original sum is =", sum_num1)
print("The total using round = ", sum_truncate1)
print("The difference from original - round =", sum_num1 - sum_truncate1)

출력:

Testing by using truncating upto 3 decimal places
The original sum is =  29985.958619386867
The total using truncate =  29486.057
The difference from original - truncate =  499.9016193868665



Testing by using round() up to 3 decimal places
The original sum is = 29985.958619386867
The total using round =  29985.912
The difference from original - round = 0.04661938686695066

원본과 잘린 후의 차이는 499.9016193868665이고 라운드에서 0.04661938686695066입니다.

그 차이가 매우 큰 것 같으며, 예제는 정확도에 가까운 계산에 도움이 되는 round() 메서드를 보여줍니다.

예:부동 소수점 숫자 반올림

이 프로그램에서는 부동 숫자에서 단어를 반올림하는 방법을 볼 것입니다.

# testing round() 

float_num1 = 10.60 # here the value will be rounded to 11 as after the decimal point the number is 6 that is >5 

float_num2 = 10.40 # here the value will be rounded to 10 as after the decimal point the number is 4 that is <=5

float_num3 = 10.3456 # here the value will be 10.35 as after the 2 decimal points the value >=5 

float_num4 = 10.3445 #here the value will be 10.34 as after the 2 decimal points the value is <5 

print("The rounded value without num_of_decimals is :", round(float_num1))
print("The rounded value without num_of_decimals is :", round(float_num2))
print("The rounded value with num_of_decimals as 2 is :", round(float_num3, 2))
print("The rounded value with num_of_decimals as 2 is :", round(float_num4, 2))

출력:

The rounded value without num_of_decimals is : 11
The rounded value without num_of_decimals is : 10
The rounded value with num_of_decimals as 2 is : 10.35
The rounded value with num_of_decimals as 2 is : 10.34

예:정수 값 반올림

정수 값에 대해 round()를 사용하면 변경 없이 숫자만 반환됩니다.

# testing round() on a integer

num = 15

print("The output is", round(num))

출력:

The output is 15

예:음수 반올림

음수에서 반올림이 작동하는 방식에 대한 몇 가지 예를 살펴보겠습니다.

# testing round()

num = -2.8
num1 = -1.5
print("The value after rounding is", round(num))
print("The value after rounding is", round(num1))

출력:

C:\pythontest>python testround.py
The value after rounding is -3
The value after rounding is -2

예:둥근 Numpy 배열

파이썬에서 numpy 배열을 반올림하는 방법은 무엇입니까?

이를 해결하기 위해 아래 예제와 같이 numpy 모듈을 사용하고 numpy.round() 또는 numpy.around() 메서드를 사용할 수 있습니다.

numpy.round() 사용

# testing round()
import numpy as np

arr = [-0.341111, 1.455098989, 4.232323, -0.3432326, 7.626632, 5.122323]

arr1 = np.round(arr, 2)

print(arr1)

출력:

C:\pythontest>python testround.py
[-0.34  1.46  4.23 -0.34  7.63  5.12]

아래 예와 동일한 결과를 제공하는 numpy.around()를 사용할 수도 있습니다.

예:10진수 모듈

round() 함수 외에도 파이썬에는 십진수를 더 정확하게 처리하는 데 도움이 되는 십진수 모듈이 있습니다.

Decimal 모듈은 아래와 같이 반올림 유형과 함께 제공됩니다.

소수에서 quantize() 메서드는 고정된 소수 자릿수로 반올림하는 데 도움이 되며 아래 예와 같이 사용할 반올림을 지정할 수 있습니다.

예:

round() 및 십진법 사용

import  decimal 
round_num = 15.456

final_val = round(round_num, 2)

#Using decimal module
final_val1 = decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_CEILING)
final_val2 = decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_DOWN)
final_val3 = decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_FLOOR)
final_val4 = decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_HALF_DOWN)
final_val5 = decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_HALF_EVEN)
final_val6 = decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_HALF_UP)
final_val7 = decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_UP)

print("Using round()", final_val)
print("Using Decimal - ROUND_CEILING ",final_val1)
print("Using Decimal - ROUND_DOWN ",final_val2)
print("Using Decimal - ROUND_FLOOR ",final_val3)
print("Using Decimal - ROUND_HALF_DOWN ",final_val4)
print("Using Decimal - ROUND_HALF_EVEN ",final_val5)
print("Using Decimal - ROUND_HALF_UP ",final_val6)
print("Using Decimal - ROUND_UP ",final_val7)

출력:

Using round() 15.46
Using Decimal - ROUND_CEILING  15.46
Using Decimal - ROUND_DOWN  15.45
Using Decimal - ROUND_FLOOR  15.45
Using Decimal - ROUND_HALF_DOWN  15.46
Using Decimal - ROUND_HALF_EVEN  15.46
Using Decimal - ROUND_HALF_UP  15.46
Using Decimal - ROUND_UP  15.46

요약:


python

  1. Python 익명/람다 함수
  2. 파이썬 생성기
  3. 파이썬 클로저
  4. 파이썬 데코레이터
  5. 예제를 사용한 C++ 연산자 오버로딩
  6. 프로그램 예제가 있는 C++ 함수
  7. Python Print() 문:예제로 인쇄하는 방법
  8. EXAMPLE이 있는 Python String strip() 함수
  9. 예제가 있는 Python 문자열 count()
  10. Python String format() 예제로 설명