2

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

E.K.
  • 23
  • 2

2 Answers2

0

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.]

Darshan
  • 71
  • 11
  • Thank you @Darshan Yes, I want the last value be "0". |-0.4| = 0.4 < 0.5 near to zero, ans = 0 |-0.6| = 0.6 > 0.5 away from zero, ans = -1 – E.K. Sep 29 '20 at 01:59
  • Yap, you solved my question~ Thanks a lot for your help ^^ – E.K. Sep 29 '20 at 09:09
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.

Default picture
  • 710
  • 5
  • 12
  • Thanks @Default picture help to answer this question so quickly. The answer which I want is correct. =) Verify and PASS – E.K. Sep 29 '20 at 09:14
  • Note that this solution also rounds values like `1.4999999999999998` (which is strictly less than `1.5`) to `2.0` instead of to `1.0`. – Mark Dickinson Sep 29 '20 at 12:33
  • @MarkDickinson Yes, but it's impossible to represent 1.5 exactly anyway – Default picture Sep 29 '20 at 23:43
  • Does tensorflow have some function let me make 1.499999999 to 1.4999 (only get % .4f) , then I can get the answer as 1? I've checked the answer in 1.4999999 is to 2 and in 1.499999 is to 1 – E.K. Sep 30 '20 at 02:16
  • @E.K. float32 precision is only 8 digits, so that's the result of floating point error. 1.5 rounds to 2, 2.5 rounds to 2 – Default picture Sep 30 '20 at 02:37
  • @Defaultpicture: "it's impossible to represent 1.5 exactly" <- Not in IEEE 754 binary32 or binary64 floating-point. 1.5 is exactly representable in every commonly-used binary, decimal, or hexadecimal floating-point system that I'm aware of. (1.1 is a different matter, of course) – Mark Dickinson Sep 30 '20 at 08:01