-2

I just started learning about Ruby and noticed that it calculated 11 / 3.0 as 3.6666666666666665.

Why wouldn't it round to "...67" like most calculators/mathematical conventions?

EDIT: Does the fact that people closed this question mean that the answer to the question is due to floating point arithmetic? I would like to know if this is the case, or if there were specific decisions about how Ruby calculates numbers.

user53
  • 21
  • 3
  • i guess...potentially? though i'm still wondering why, if a calculator is a computer and it can give the right answers, why aren't programming languages built according to the same standard? – user53 Mar 25 '20 at 22:59
  • i also heard someone say, "Ruby division rounds down," so it sounded like this was a conscious programming decision when making the language and so i wanted to know why – user53 Mar 25 '20 at 23:02
  • https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Dave Newton Mar 26 '20 at 00:52
  • @user53: Calculators do have the same limitations, if they use the same floating point implementation, which most do. – Jonathan Hall Mar 26 '20 at 07:36
  • "Does the fact that people closed this question mean that the answer to the question is due to floating point arithmetic?" Yes. Every other language that uses IEEE floating point numbers (the vast majority) exhibits the exact same behavior. Examples: [Go](https://play.golang.org/p/N1JT-3B2q-F), [JavaScript](https://jsfiddle.net/gv4sncom/). – Jonathan Hall Mar 26 '20 at 07:40
  • My instructor just said: “That’s just the implementation that the developers of Ruby chose to go with, I don’t believe there’s a particular reason. In other languages, division may just return a float number, in other languages it may round up.” any insight into why they would choose this instead of to round up? – user53 Mar 27 '20 at 01:31

1 Answers1

1

It's for people who want to be really precise.

You can use

(11/3.0).round(2)

It gives like you asked for 3.67

Apidock link for round

Semih Arslanoglu
  • 1,069
  • 5
  • 20
  • 23
  • interesting; thank you! though i was wondering why it chooses that last digit, at the end of all those 6's, to be 5 and not 7. Seems 7 would more closely approximate than 5. – user53 Mar 25 '20 at 22:56