Welcome to the Treehouse Community
Looking to learn something new?
Jeff Lange8,788 Points
Ruby does not seem to be performing mathematical operations properly
As part of my morning exercise, which was SUPPOSED to be quick, I created a volume-of-a-sphere calculator using the well-known forumula: 4/3 pi r^3.
I represented this in my code as:
volume = ((4/3) * (Math::PI) * (radius**3))
However, when checking the answer Ruby returned, I saw it was wrong. Examination showed me that Ruby was multiplying PI and radius**3, but leaving out 4/3 entirely.
If I remove the parentheses AND I put 4/3 in the middle than Ruby will return the right answer, but if 4/3 is first and/or I use parentheses, it will leave it out again. So the code works like this:
volume = Math::PI * 4/3 * radius**3
Hence, it's nearly identical to the first. What on earth is going on? There is no reason for Ruby to decide to randomly leave out one of your expressions. Any ideas what on earth is going on???
Nicholas OlsenFront End Web Development Techdegree Student 19,342 Points
This is a good question!
In your first example (4/3) [in parentheses] returns 1 and not 1.3333…
In your second example, Math::PI is multiplied by 4 [which returns a float] then divided by three. Which, mathematically speaking, is the same thing.
So the way to solve this is to convert 4/3 into a floating point number. Maybe you can do this simply by representing 4/3 as 1.33333333 in your formula or (perhaps better) ruby has some function to convert 4/3 into an float for you. Check the documentation here on float and maybe you can find something.
edit: Another option is to change 4/3 to 4.0/3.0
Sreng Hong15,083 Points
There is no magic for sure. :D
I think what's going on here, because
4/3 will return
In the first codes you use the parenthesis, so Ruby will calculate only
(Math::PI) * (radius**3). That's why you got the incorrect answer.
In the second codes you don't use parenthesis and also move 4/3 to the middle, so what Ruby do is it will multiple Math::PI with 4 then divide with 3... That's why you got the correct answer.
Do you get the ideas?
Jeff Lange8,788 Points
Ok, so does this mean Ruby was treating the result of 4/3 as an integer instead of a float, and therefore was dropping the decimals?
Ok, thank you so much, guys. I tested it in irb, and sure enough, 4/3 returned 1, but 4.0/3.0 returned 1.33333_. So glad this actually makes sense. Thanks again.