Then We fetch the square root from the Hash, avoiding sqrt, when possible. We reduce an operation to a lookup.
Tip For slow computations, this can improve performance. But it will make fast computations slower than before.
def check_sqrt(a, cache)
# See if the cache contains a square root for this argument.
# Compute square root and memoize it.
cache[a] = Math.sqrt(a)
# Use memoize square root method with Hash.
cache = Hash.new()
puts check_sqrt(9, cache)
puts check_sqrt(9, cache)3.0
Floor, ceil. The floor and ceil methods are not part of the Math module. We call them directly on a number instance. Here we set a number to 1.1 and use floor and ceil.
Info Floor changes 1.1 to 1, and ceil changes 1.1 to 2. The methods go lower and higher to the next integer.
number = 1.1
# Use floor to remove the fractional part.
result1 = number.floor
# Use ceil to move to the next highest integer.
result2 = number.ceil
Truncate. A number can have a fractional part. The number 1.99 has a fractional part of ".99." With truncate the fractional part is eliminated from the number.
And No other changes are made. Truncate can work on positive or negative numbers.
number = 1.99
# Truncate removes the fractional part.
result = number.truncate
# Negative numbers can be truncated too.
number = -1.99
Round. On Floats we can use the round() method. This returns the nearest integral value to the value stored by the float. It may move the total value lower or higher.