How to return a simpler approximation of a float value in Ruby
Overview
We can return a simpler approximation of a float value by using the rationalize() method.
Syntax
# default
float_value.rationalize
# with option
float_value.rationalize(opt)
Parameters
-
float_value: This is the float value whose simple approximation we want to get. -
opt: This is an optional parameter. When this is passed, the approximation result becomesfloat_value-opt<= result <= float_value+opt. It means that the results are in between the subtraction of the option from the float value, and the sum of the float value and option.
Return value
This method returns a simple approximation of float_value.
Example
# create float valuesf1 = 23.3f2 = 0.2f3 = 100.5f4 = -3.00# rationalize valuesr1 = f1.rationalizer2 = f2.rationalizer3 = f3.rationalize(2.00)r4 = f4.rationalize(0.01)# print resultsprint "#{r1}\n"print "#{r2}\n"print "#{r3}\n"print "#{r4}\n"
Explanation
In the above code snippet:
- Lines 2 to 5: We create float variables and initialize them with values.
- Lines 8 to 11: We invoke the
rationalize()method on the float values. - Lines 14 to 17: We print the results which are simple approximations to the console.