14
Zum Beispiel, wenn ich 98/42
berechnen möchte ich 7/3
, nicht 2.3333333
, gibt es eine Funktion für die Verwendung von Python oder Numpy
?Hat Python eine Funktion zum Reduzieren von Brüchen?
Zum Beispiel, wenn ich 98/42
berechnen möchte ich 7/3
, nicht 2.3333333
, gibt es eine Funktion für die Verwendung von Python oder Numpy
?Hat Python eine Funktion zum Reduzieren von Brüchen?
Das kann fractions
Modul tun
>>> from fractions import Fraction
>>> Fraction(98, 42)
Fraction(7, 3)
Es über here für eine numpy gcd ein Rezept ist. Welche können Sie dann verwenden, um Ihre Fraktion zu teilen
>>> def numpy_gcd(a, b):
... a, b = np.broadcast_arrays(a, b)
... a = a.copy()
... b = b.copy()
... pos = np.nonzero(b)[0]
... while len(pos) > 0:
... b2 = b[pos]
... a[pos], b[pos] = b2, a[pos] % b2
... pos = pos[b[pos]!=0]
... return a
...
>>> numpy_gcd(np.array([98]), np.array([42]))
array([14])
>>> 98/14, 42/14
(7, 3)
Vielen Dank! Funktioniert super! Der Eingabewert muss Ganzzahlen sein, kann nicht float sein. – LWZ