<< Back to RUBY
Ruby Math Examples: floor, ceil, round and truncate
Use mathematical functions like floor, ceil and truncate. Compute square roots.Math. A stone tablet is covered in dust. On it you read an inscription. It also has some mathematical markings but you start feeling sleepy.
In Ruby we invoke built-in Math functions. Sqrt returns a square root. The sin, cos and tan methods relate parts of a triangle. There are two constants: PI and E.
Constants. Here we call Math methods and use Math constants. This program uses sqrt() on 9, which returns 3. It also prints PI, equal to 3.14, and E, equal to 2.71.
Methods: Please notice how the Math methods, such as sqrt(), use a period after Math.
Constants: To access constants in a module, like PI, we use the Math::PI syntax. Math::E uses the same syntax.
Ruby program that uses Math
# Use sqrt.
# ... Square root of 9 is 3.
x = Math.sqrt(9)
puts x
# Use pi.
puts Math::PI
# Use e.
puts Math::E
Output
3.0
3.141592653589793
2.718281828459045
Absolute values. These are never negative. The abs method takes absolute values of numbers. It is not part of the Math class—we do not use the Math module name here.
Result: If the number is negative, abs will return a positive version. It also handles floating point numbers.
Ruby program that uses abs
# Take absolute values.
value = -1
puts value.abs
value = -1.1
puts value.abs
value = 1
puts value.abs
Output
1
1.1
1
Sin, cos and tan. Trigonometric functions are available in the Math module. These provide standard results—the cos of zero, for example, is 1.
Quote: In mathematics, the trigonometric functions [are] functions of an angle. They relate the angles of a triangle to the lengths of its sides.
Trigonometric functions: WikipediaRuby program that uses sin, cos and tan
# Math provides sin, cos and tan methods.
puts Math::sin(0)
puts Math::cos(0)
puts Math::tan(0)
Output
0.0
1.0
0.0
Memoization. Sometimes Math methods, and more complex calculations involving many calls, are slow. We can use a memoization approach to avoid calculating the same thing twice.
Here: We use a cache (a Hash) and check to see if it contains the square root of the argument.
HashThen: 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.
Ruby program that uses memoization, sqrt
def check_sqrt(a, cache)
# See if the cache contains a square root for this argument.
if cache.key?(a)
return cache[a]
end
# Compute square root and memoize it.
cache[a] = Math.sqrt(a)
return cache[a]
end
# Use memoize square root method with Hash.
cache = Hash.new()
puts check_sqrt(9, cache)
puts check_sqrt(9, cache)
Output
3.0
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.
Ruby program that uses floor, ceil
number = 1.1
puts number
# Use floor to remove the fractional part.
result1 = number.floor
puts result1
# Use ceil to move to the next highest integer.
result2 = number.ceil
puts result2
Output
1.1
1
2
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.
Ruby program that uses truncate
number = 1.99
puts number
# Truncate removes the fractional part.
result = number.truncate
puts result
# Negative numbers can be truncated too.
number = -1.99
puts number.truncate
Output
1.99
1
-1
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.
Ruby program that uses round
number_a = 1.234
number_b = -1.234
number_c = 1.99
number_d = -1.99
puts ":::ROUND number_a, number_b :::"
# Use round method.
puts number_a.round
puts number_b.round
puts ":::ROUND number_c, number_d :::"
# The nearest integer is returned.
puts number_c.round
puts number_d.round
Output
:::ROUND number_a, number_b :::
1
-1
:::ROUND number_c, number_d :::
2
-2
Fibonacci numbers. In the Fibonacci sequence, each number is equal to the two previous numbers added together. This sequence occurs often in nature. And we can compute it with an iterator.
Fibonacci
A summary. Certain mathematical methods, such as sqrt() and trigonometric identities, are rarely implemented in user code. Ruby provides these methods.
As an optimization, we can cache their results in a lookup table. This classic optimization is known as memoization. A function remembers its previous results by argument.
Related Links:
- Ruby Convert Types: Arrays and Strings
- Ruby File Handling: File and IO Classes
- Ruby Regexp Match Method
- Ruby String Array Examples
- Ruby include: Array Contains Method
- Ruby Class Examples: Self, Super and Module
- Ruby DateTime Examples: require date
- Ruby 2D Array Examples
- Ruby Number Examples: Integer, Float, zero and eql
- Ruby Exception Examples: Begin and Rescue
- Top 65 Ruby Interview Questions (2021)
- Ruby on Rails Interview Questions (2021)
- Ruby String Examples (each char, each line)
- Ruby if Examples: elsif, else and unless
- Ruby Math Examples: floor, ceil, round and truncate
- Ruby Sub, gsub: Replace String
- Ruby Substring Examples
- Ruby Console: Puts, Print and stdin
- Ruby Remove Duplicates From Array
- Ruby Random Number Generator: rand, srand
- Ruby Recursion Example
- Ruby ROT13 Method
- Ruby Iterator: times, step Loops
- Ruby String Length, For Loop Over Chars
- Ruby Join Example (Convert Array to String)
- Ruby Format String Examples
- Ruby Copy Array Example
- Ruby Keywords
- Ruby Nil Value Examples: NoMethodError
- Learn Ruby Tutorial
- Ruby Method: Def, Arguments and Return Values
- Ruby Fibonacci Sequence Example
- Ruby Hash Examples
- Ruby While, Until and For Loop Examples
- Learn Ruby on Rails Tutorial
- Ruby Word Count: Split Method
- Ruby Sort Arrays (Use Block Syntax)
- Ruby Case Examples: Ranges, Strings and Regexp
- Ruby Array Examples
- Ruby Split String Examples
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf