Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Math methods
- # Arithmetic - exponentiation (**) and modulus (%)
- puts 5**2 # "five squared'
- puts 5**0.5 # floats for your expomemt, so if you want the square root of 5
- puts 7/3
- puts 7%3 # remainder after division of a number
- puts 365%7 # a (non-leap) year has some number of weeks, plus one day. So if your birthday was on a Tuesday this year, it will be on a Wednesday next year.
- # You can also use floats with the modulus method.
- puts 365%7.to_f
- # absolute value of a number (abs)
- puts((5-2).abs)
- puts((2-5).abs)
- # random number generator - rand
- # get a float greater than or equal to 0.0 and less than 1.0. If you give rand an integer (5 for example), it will give you an integer greater than or equal to 0 and less than 5 (so five possible numbers, from 0 to 4).
- puts rand
- puts rand
- puts rand
- puts(rand(100))
- puts(rand(100))
- puts(rand(100))
- puts(rand(1))
- puts(rand(1))
- puts(rand(1))
- puts(rand(9999999999999999999999999999))
- puts('The weatherman said there is a '+rand(101).to_s+'% chance of rain,')
- puts('but you can never trust a weatherman.')
- # same number of random numbers in the same sequence on two different runs of your program (For example, once I was using randomly generated numbers to create a randomly generated world for a computer game. If I found a world that I really liked, perhaps I would want to play on it again, or send it to a friend.) In order to do this, you need to set the seed
- srand 1776
- puts(rand(100))
- puts(rand(100))
- puts(rand(100))
- puts(rand(100))
- puts(rand(100))
- puts ''
- srand 1776
- puts(rand(100))
- puts(rand(100))
- puts(rand(100))
- puts(rand(100))
- puts(rand(100)) # If you want to get different numbers again (like what happens if you never use srand), then just call srand 0. This seeds it with a really weird number, using (among other things) the current time on your computer, down to the millisecond.
- # math objects
- puts(Math::PI) # :: is the scope operatior
- puts(Math::E)
- puts(Math.cos(Math::PI/3))
- puts(Math.tan(Math::PI/4))
- puts(Math.log(Math::E**2))
- puts((1 + Math.sqrt(5))/2)
Add Comment
Please, Sign In to add comment