-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram.py
More file actions
54 lines (42 loc) · 1.83 KB
/
program.py
File metadata and controls
54 lines (42 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def get_sign(num):
# Shift the sign bit of the integer to the rightmost position
sign_bit = num >> 31
# Use the sign bit to determine the sign:
# If the number is positive, sign_bit will be 0 (0000...0000).
# If the number is negative, sign_bit will be -1 (1111...1111).
# If the number is zero, the sign_bit will remain 0.
# We can then use the absolute value of sign_bit as the sign representation.
sign = 1 - ((sign_bit + sign_bit) & 1)
return sign
def min_branchless(a, b):
# Calculate the difference between a and b
diff = a - b
# Calculate the sign bit of the difference
sign_bit = diff >> 31
# If a is less than b, the sign_bit will be -1 (1111...1111).
# If a is greater than or equal to b, the sign_bit will be 0 (0000...0000).
# In the case where a is less than b, we will add the difference to b.
# Otherwise, we will add 0 to b, effectively keeping b as the minimum.
min_value = b + (diff & sign_bit)
return min_value
def is_smaller(a, b):
# Check if a is smaller than b
return (a - b) < 0
def min_with_helper(a, b):
# If is_smaller(a, b) returns true, then a is smaller than b.
# In this case, we will return a + 0, effectively keeping a as the minimum.
# Otherwise, if is_smaller(a, b) returns false, then a is greater than or equal to b.
# In this case, we will return a + (b - a), which will be equal to b.
# This effectively returns the smaller of the two values.
return a + (b - a) * int(is_smaller(a, b))
# Test the functions
num1 = 42
num2 = -7
num3 = 0
print(f"Sign of {num1}: {get_sign(num1)}")
print(f"Sign of {num2}: {get_sign(num2)}")
print(f"Sign of {num3}: {get_sign(num3)}")
a = 15
b = 9
print(f"Minimum of {a} and {b} (branchless): {min_branchless(a, b)}")
print(f"Minimum of {a} and {b} (with helper): {min_with_helper(a, b)}")