Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is python calculation with float numbers faster than calculation with integer numbers

This example shows that python calcuation with float numbers is faster than with integer numbers. I am wondering why calculation with integer is not faster than with float

import time
# Number of operations
N = 10**7

# Integer addition
start_time = time.time()
int_result = 0
for i in range(N):
    int_result += 1
int_time = time.time() - start_time

# Float addition
start_time = time.time()
float_result = 0.0
for i in range(N):
    float_result += 1.0
float_time = time.time() - start_time

print(f"Time taken for integer addition: {int_time:.6f} seconds")
print(f"Time taken for float addition: {float_time:.6f} seconds")
like image 945
tamnva Avatar asked Dec 21 '25 06:12

tamnva


1 Answers

float is a thin wrapper around whatever floating-point type your hardware provides. int is not; it's an arbitrary-precision type based on arrays of large "digits". A "small" integer is still a single-element array of machine words, rather than a single machine word itself. Operations on such values are necessarily slower than a single machine-integer operation would be.

like image 194
chepner Avatar answered Dec 23 '25 19:12

chepner