Ich frage mich, ob jemand kann mir jeder Einblick, wie die folgenden können gleich/unterschiedlich in sein Python3:Math.floor (N) vs N // 1
N // 1
und
from math import floor
floor(N)
ich habe versucht, die folgende, die dass sie gleichwertig sind, um anzuzeigen, scheint:
import math
import random
for _ in range(0, 99999):
f = random.random()
n = random.randint(-9999, 9999)
N = f * n
n_div = N // 1; n_mth = math.floor(N)
if n_div != n_mth:
print("N // 1: {} | math.floor(N): {}".format(n_div, n_mth))
else: # yes, I realize this will always run
print("Seem the same to me")
Danke für die Kommentare unten. Aktualisierter Test zu den folgenden, die deutlich zeigt float // N
gibt eine float
zurück, während math.floor(N)
eine int
in python3 zurückgibt. Wie ich es verstehe, ist dieses Verhalten unterschiedlich in python2, wo math.ceil
und math.floor
zurück float
s.
Beachten Sie auch, wie ungewöhnlich/albern es math.ceil
oder math.floor
auf einem int
anstelle eines float
zu verwenden wäre: entweder Funktion auf einem int
gibt einfach, dass int
arbeitet.
import math
import random
for _ in range(0, 99):
N = random.uniform(-9999, 9999)
n_div = N // 1; n_mth = math.floor(N)
if n_div != n_mth:
print("N: {} ... N // 1: {} | math.floor(N): {}".format(N, n_div, n_mth))
elif type(n_div) != type(n_mth):
print("N: {} ... N // 1: {} ({}) | math.floor(N): {} ({})".format(N, n_div, type(n_div), n_mth, type(n_mth)))
else:
print("Seem the same to me")
Es ist alles gleich. –
'//' gibt ein 'float' zurück und' floor' gibt ein 'int' zurück? –
@tobias_k in Python 3, 'math.float()' und 'math.ceil()' return 'ints' – NotAnAmbiTurner