Skip to content

Commit 46fcbe7

Browse files
authored
Enforce int types in math.factorial (qutip#1550)
Using integer-like floats in math.factorial is deprecated as of Python 3.9. The arbitrary precision nature of Python ints is still desirable here.
1 parent c5be0ee commit 46fcbe7

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

qutip/piqs.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,18 @@
102102
"Pim",
103103
]
104104

105+
106+
def _ensure_int(x):
107+
"""
108+
Ensure that a floating-point value `x` is exactly an integer, and return it
109+
as an int.
110+
"""
111+
out = int(x)
112+
if out != x:
113+
raise ValueError(f"{x} is not an integral value")
114+
return out
115+
116+
105117
# Functions necessary to generate the Lindbladian/Liouvillian
106118
def num_dicke_states(N):
107119
"""Calculate the number of Dicke states.
@@ -641,8 +653,8 @@ def energy_degeneracy(N, m):
641653
The energy degeneracy
642654
"""
643655
numerator = Decimal(factorial(N))
644-
d1 = Decimal(factorial(N / 2 + m))
645-
d2 = Decimal(factorial(N / 2 - m))
656+
d1 = Decimal(factorial(_ensure_int(N / 2 + m)))
657+
d2 = Decimal(factorial(_ensure_int(N / 2 - m)))
646658
degeneracy = numerator / (d1 * d2)
647659
return int(degeneracy)
648660

@@ -671,8 +683,8 @@ def state_degeneracy(N, j):
671683
if j < 0:
672684
raise ValueError("j value should be >= 0")
673685
numerator = Decimal(factorial(N)) * Decimal(2 * j + 1)
674-
denominator_1 = Decimal(factorial(N / 2 + j + 1))
675-
denominator_2 = Decimal(factorial(N / 2 - j))
686+
denominator_1 = Decimal(factorial(_ensure_int(N / 2 + j + 1)))
687+
denominator_2 = Decimal(factorial(_ensure_int(N / 2 - j)))
676688
degeneracy = numerator / (denominator_1 * denominator_2)
677689
degeneracy = int(np.round(float(degeneracy)))
678690
return degeneracy

0 commit comments

Comments
 (0)