TKVR

Chris Pine, Learn to Program Chapter 5 Pt. 2 - Math

Feb 16th, 2012
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 2.03 KB | None | 0 0
  1. # Math methods
  2. # Arithmetic - exponentiation (**) and modulus (%)
  3. puts 5**2 # "five squared'
  4. puts 5**0.5 # floats for your expomemt, so if you want the square root of 5
  5. puts 7/3
  6. puts 7%3 # remainder after division of a number
  7. 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.
  8. # You can also use floats with the modulus method.
  9. puts 365%7.to_f
  10.  
  11. # absolute value of a number (abs)
  12. puts((5-2).abs)
  13. puts((2-5).abs)
  14.  
  15. # random number generator - rand
  16. # 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).
  17. puts rand
  18. puts rand
  19. puts rand
  20. puts(rand(100))
  21. puts(rand(100))
  22. puts(rand(100))
  23. puts(rand(1))
  24. puts(rand(1))
  25. puts(rand(1))
  26. puts(rand(9999999999999999999999999999))
  27. puts('The weatherman said there is a '+rand(101).to_s+'% chance of rain,')
  28. puts('but you can never trust a weatherman.')
  29.  
  30. # 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
  31. srand 1776
  32. puts(rand(100))
  33. puts(rand(100))
  34. puts(rand(100))
  35. puts(rand(100))
  36. puts(rand(100))
  37. puts ''
  38. srand 1776
  39. puts(rand(100))
  40. puts(rand(100))
  41. puts(rand(100))
  42. puts(rand(100))
  43. 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.
  44.  
  45. # math objects
  46. puts(Math::PI) # :: is the scope operatior
  47. puts(Math::E)
  48. puts(Math.cos(Math::PI/3))
  49. puts(Math.tan(Math::PI/4))
  50. puts(Math.log(Math::E**2))
  51. puts((1 + Math.sqrt(5))/2)
Add Comment
Please, Sign In to add comment