Shpigford
Shpigford

Reputation: 25338

Convert Infinity to 0 with Ruby

Is there a method to convert Infinity to 0?

If a calculation returns Infinity, I want to represent it as 0. I tried to use to_i as in (+1.0/0.0).to_i, but that threw a FloatDomainError error.

Upvotes: 0

Views: 1796

Answers (6)

sbagdat
sbagdat

Reputation: 850

You can use string interpolation for this:

"#{+1.0/0.0}".to_i  #=> 0

Upvotes: 1

user4913752
user4913752

Reputation: 1

Use 0.0 || 1.0/0.0, this will not work

Upvotes: 0

Wayne Conrad
Wayne Conrad

Reputation: 107979

There are two infinities: positive, and negative. The method Float#infinite? returns +1 for positive infinity, -1 for negative infinity, and nil if the number is neither. So:

if f.infinite?
  f = 0
end

This works because +1 and -1 are both truthy values, and nil is a falsy value.

If it is only positive infinity you wish to replace with zero, then:

if f.infinite? == 1
  f = 0
end

and similarly for negative infinity.

If the number might be an integer or some other kind of Numeric that is not a float, then convert it to a float first:

if f.to_f.infinite?
  f = 0
end

Upvotes: 2

eToThePiIPower
eToThePiIPower

Reputation: 185

You could try testing using infinite?. Something like the following:

def no_infinites num
  num.to_f.infinite? ? 0 : num
end

This returns 0 if num is ±Infinity, and num otherwise. The return value will be whatever type num is if num is finite

Upvotes: 0

Phrogz
Phrogz

Reputation: 303206

result = 1.0/0 #=> Infinity
result.to_f.infinite? ? 0 : result

Upvotes: 0

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

 > x = (+1.0/0.0)
 => Infinity
 > x = 0 if x.infinite?
 => 0
> x
 => 0

Upvotes: 3

Related Questions