I have some question when doing tf.round(x) x=[0.4, 1.5, 2.5, -1.5, -2.5, -0.4]
If I want to get the ans=[0, 2, 3, -2, -3, 0] rounding half way away from zero
How should I do? I've tried tf.keras.backend.round(), tf.math.round, tf.math.rint()
I got similar answer in python but not in TF
>>>decimal.Decimal(101.5).quantize(decimal.Decimal('0'), rounding=decimal.ROUND_HALF_UP)
Decimal('102')
>>>decimal.Decimal(102.5).quantize(decimal.Decimal('0'), rounding=decimal.ROUND_HALF_UP)
Decimal('103')
>>>decimal.Decimal(-101.5).quantize(decimal.Decimal('0'), rounding=decimal.ROUND_HALF_UP)
Decimal('-102')
>>>decimal.Decimal(-102.5).quantize(decimal.Decimal('0'), rounding=decimal.ROUND_HALF_UP)
Decimal('-103')
Thank you
How about this ?
x = np.array([0.4, 1.5, 2.5, -1.5, -2.5, -0.4])
for i, val in enumerate(x):
if val % 1 == 0.5
x[i] = tf.math.floor(x[i]) if val < 0 else tf.math.floor(x[i]+0.5)
else
x[i] = tf.math.round(x[i])
print(x)
[ 0. 2. 3. -2. -3. 0.]
Try
x=tf.constant([0.4, 1.5, 2.5, -1.5, -2.5, -0.4])
x=tf.where(x>0, tf.math.nextafter(x, np.inf), tf.math.nextafter(x, -np.inf))
x=tf.round(x)
this will round away from 0.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.