Ruby arithmetic operations =S

Hi there

I have to do a program for the first time that needs some math…and
which is my surprise that num mod num to get the modulus of a division
does not work! neither num div num to the the integer result of it.

All the rest of math operands work fine xDDD But how do i do:

a) A float division ( 5 / 2 = 2.5)
b) A mod division ( 5 mod 2 = 1)
c) An integer division =S (5 div 2 = 2)

Thx! xD

All the rest of math operands work fine xDDD But how do i do:

a) A float division ( 5 / 2 = 2.5)
b) A mod division ( 5 mod 2 = 1)
c) An integer division =S (5 div 2 = 2)

5 / 2.0
=> 2.5

5 % 2
=> 1

5 / 2
=> 2

In ruby when you divide integers, you get integer division. If you
want float, use floats (just add
point zero).

Regards,
Rimantas

Flaab M. wrote:

Hi there

I have to do a program for the first time that needs some math…and
which is my surprise that num mod num to get the modulus of a division
does not work! neither num div num to the the integer result of it.

All the rest of math operands work fine xDDD But how do i do:

a) A float division ( 5 / 2 = 2.5)

5.0 / 2.0 = 2.5

b) A mod division ( 5 mod 2 = 1)

5 % 2 = 1

c) An integer division =S (5 div 2 = 2)

5 / 2 = 2

The point is, you tell the language what you want by specifying the
numeric
type. Floats have a decimal point and one or more digits to the right,
even
if only a zero. Integers don’t.

5 / 2.0
=> 2.5

5 % 2
=> 1

5 / 2
=> 2

In ruby when you divide integers, you get integer division. If you
want float, use floats (just add
point zero).

It’s not quite so simple.

5/2
=> 2

require ‘mathn’
=> true

5/2
=> 5/2
…where the last “5/2” is a rational number. If you want to do
integer division “portably” (i.e., in a way that is compatible with the
mathn standard library having been required earlier in the program),
you should use “div”

5.div(2)
=> 2

5.modulo(2)
=> 1

5.divmod(2)
=> [2,1]
If you wish to use the Rational, Complex, or Matrix classes in the
standard library, you will need to require mathn to avoid strange and
even downright buggy behavior. But this redefines the meaning of
expressions like 5/2.

----- Original Message -----
From: “Flaab M.” [email protected]
Newsgroups: comp.lang.ruby
To: “ruby-talk ML” [email protected]
Sent: Thursday, November 16, 2006 5:46 PM
Subject: Ruby arithmetic operations =S

c) An integer division =S (5 div 2 = 2)

Thx! xD


Posted via http://www.ruby-forum.com/.

float division x = 5.0 / 2 or x = 5 /2.0 or x 5.0/2.0
mod division x = 5 % 2
integer division x = 5 / 2