Skip to content

Commit 862dc4f

Browse files
committed
python math problems
1 parent d70ef56 commit 862dc4f

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import math
2+
3+
# Division is decimal by default
4+
print('5 / 2 = ', 5 / 2)
5+
# output => 2.5
6+
7+
# Double slash rounds down to integer
8+
print('5 // 2 = ', 5 // 2)
9+
# output => 2
10+
11+
# CAREFUL: most languages round towards 0 by default
12+
# python rounds towards minimum value
13+
# So negative numbers will round down
14+
print('-3 // 2 = ', -3 // 2)
15+
# output => -2 but it should be -1
16+
17+
# A workaround for rounding towards zero
18+
# is to use decimal division and then convert to int.
19+
print('-3 // 2 = ', int(-3 / 2))
20+
# output => -1
21+
22+
# Modding is similar to most languages
23+
print('10 % 3 = ', 10 % 3)
24+
# output => 1
25+
26+
# Except for negative values
27+
print('-10 % 3 = ', -10 % 3)
28+
29+
# To be consistent with other languages modulo use math fmod
30+
31+
print(math.fmod(-10, 3))
32+
33+
# More math helpers
34+
print(math.floor(3 / 2)) # rounds down
35+
print(math.ceil(3 / 2)) # rounds up
36+
print(math.sqrt(2))
37+
print(math.pow(2, 3))
38+
39+
# Max / Min Int
40+
float("inf")
41+
float("-inf")
42+
43+
# Python numbers are infinite so they never overflow
44+
print(math.pow(2, 200))
45+
46+
# But still less than infinity
47+
print(math.pow(2, 200) < float("inf"))
48+
# output => True

0 commit comments

Comments
 (0)