3.4 Basic Arithmetic Operators

Now that some of the classes that define various data types have been introduced, what can you do with them? Like all other programming languages, Ruby is able to perform many mathematical operations. In Table 3-1, we illustrate how to use Ruby as a calculator.

Table 3-1. Basic arithmetic operators

Symbol

Operation

Example

+

Addition

x = 6 + 2

8

-

Subtraction

x = 3 - 2

1

*

Multiplication

x = 5 * 2

10

/

Division

x = 16/8

2

%

Modulus

x = 5 % 3

2

**

Power

x = 2 ** 4

16

All of the operators listed are binary operators, meaning the operator has two operands. For example, the command A + B is a binary operation, where A and B are the two operands and + is the operator.

When typing mathematical operations in the Ruby interpreter, the order of operations is taken into account. To change the order of operations, use parentheses. Try typing the following in the command line:

irb(main):001:0> x = 10 + 4 / 2

What result did you get? Now try entering the following into the prompt:

irb(main):001:0> x = (10 + 4) / 2

Most of the operators should look familiar. The one that might not is the modulus operator (%). The purpose of this operator is to find the remainder produced by dividing two numbers. For example, 4 modulo 2, abbreviated 4 mod 2, would produce the result 0. This is because 4 / 2 is exactly 2. On the other hand, 2 mod 4 produces a result of 2. This is because 2 / 4 is 0, with a remainder of 2. Let’s try to solve a few easy problems using the modulus operator.

  1. Using the mod operator, determine if a number is even. This should be fairly easy. We know that n is even if, when divided by 2, it produces a remainder of 0. So, if n mod 2 equals 0, then n is even.

    irb(main):001:0> x = 5%2
    => 1
    irb(main):002:0> x = 6%2
    => 0
  2. Given a number as input, determine if the number is prime. That is, the given number must not have any factors other than 1 and itself. For example, 1, 3, 5, and 7 are prime numbers. The number 2 is the only even prime number since all other even numbers have 2 as a factor. Likewise, for example, the number 9 is also not prime since 3 divides it evenly. As an aside, finding prime numbers is one of the classic problems used to teach any programming language. Furthermore, prime numbers play a significant role in information security. For example, SSL (Secure Sockets Layer), which is what you use when you go to a website and type “https”, uses an algorithm called public key encryption. This algorithm relies heavily on prime numbers. The intuition behind the use of prime numbers is that for long numbers (those that comprise hundreds of digits) it takes a computer a very long time to determine their factors. Thus, it is safe to publicly present these numbers.

    Although we may not be able to program this yet, we can come up with an algorithm to solve this problem. Namely, we can do the following:

    If n is equal to 2, then n is prime. Otherwise, take each number x in the range 2 to n – 1. If n mod x is equal to 0 for any of these numbers x, then the number n is not prime. If n mod x is not equal to 0 for every number in the range 2 to n – 1, then the number n is prime.

    Note that this is not an efficient algorithm, but it is correct. Can you think of a more efficient approach? Hint: Do we really need to check all the way up to n – 1?

Gem of Wisdom

Components of a mathematical expression can usually be broken into operands and operators. For example, in the expression 2 + 3, 2 and 3 are operands, and + is the operator. Operands are usually values, and operators are the actions to be performed.

Now that we have discussed the basics, we will describe some slightly more advanced operations. Ruby has many built-in modules; a module is simply a group of methods for a particular domain. There are methods that accomplish many different tasks. We will discuss methods in great detail starting with Chapter 8. For example, Ruby has a built-in module for mathematics, the Math module. Table 3-2 lists some of the more advanced mathematical functions in Ruby. These functions are referred to as methods.

Table 3-2. Advanced arithmetic operations

Method

Operation

Example

Result

sqrt()

Square root

x = Math.sqrt(9)

3.0

sin()

Sine

x = Math.sin(0)

0.0

cos()

Cosine

x = Math.cos(0)

1.0

tan()

Tangent

x = Math.tan(0.7854)

1.0

log()

Natural log (ln)

x = Math.log(5)

1.609

log10()

Log (base 10)

x = Math.log10(10)

1.0

When trying to perform these operations, we specify the Math module, followed by a period (.), then the method (type of operation). For example, to find the square root of 16, type:

irb(main):001:0> x = Math.sqrt(16)
=> 4.0

To appreciate the power of the Math module and understand the order of operations in Ruby, try creating a program that performs the following operation:

Advanced arithmetic operations

The result should look similar to this:

irb(main):001:0> x = (5 + Math.sqrt(9)) / 2
=> 4.0

Make sure you obtain 4.0 as a result. If you do not, try again. With computers there is no point in repeating failure precisely. Often, novice programmers state: “Well, I tried it 500 times!” If no input was changed, rest assured that no output will change either. So change something and then try again! Be patient, check things carefully, and keep working until the result is 4.0. If you obtained 4.0 the first time, try some variations (e.g., misspell the word Math), and become familiar with some error messages. It is important to start being methodical about implementing programs on a computer on the very first day. Take your time, go slowly, and think about everything you enter. Sometimes with programming languages even the smallest detail can be the difference between success and failure.

Gem of Wisdom

Ruby comes with many built-in functions called methods to make your life easier. Table 3-2 shows a few of them. Without a square root (i.e., sqrt()) function you would need to write a program to compute the square root by repeated division. For any programming language, make sure you learn about all the built-in functions, as they can save you significant time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.239.214