How to change python way of casting float('inf') to str?

Viewed 273

My app is processing numbers, and of them are pythons float('inf'). The problem is that I'd like for such number to be casted as full word: "Infinity".

for x in [float('inf'), float(5.0)]:
    print(x)

Results with:

inf
5.0

I would like it to be:

Infinity
5.0

Can I somehow set how infinity is represented in string?

Of course I could make something like method below:

def cast_num(num):
    if num == float('inf')
        return 'Infinity'
    else:
        return str(num)

But such method is costly - It has to process every number.

Is there better alternative?

Is there some flag in python which I can set? (like 'setlocale')

2 Answers

Using numpy, this might be a good solution for you:

import numpy as np

x = np.array([2.0, float('inf'), 5.0], dtype='<U8')

x[x=='inf'] = 'Infinity'
x

Another way is to use a simple dictionary :

values = {float('inf'):'Infinity'}
i = float('inf')
p = 0.5
print(values.get(i, str(i)))
print(values.get(p, str(p)))

Output

Infinity
0.5
Related