user1683526
user1683526

Reputation: 79

Function giving slightly different answer than expected

I'm doing some monad stuff in Haskell and I wrote a function that calculates the probability of winning a gambling game given the game's decision tree. It works like a charm, except for the fact that it sometimes returns SLIGHTLY different answers than expected. For example, I'm uploading my code to DOMjudge and it returns an error, saying that the correct answer should be 1 % 6 instead of 6004799503160661 % 36028797018963968, which is what my function is returning. If you actually do the division they're both nearly the same, but I don't understand why my answer is still slightly different. I've been messing around with different types (using Real instead of Int for example), but so far no luck. I'm kind of new to this stuff and I can't seem to figure this out. Can anyone point me in the right direction?

-code deleted-

Upvotes: 2

Views: 458

Answers (1)

J. Abrahamson
J. Abrahamson

Reputation: 74334

You're losing precision due to the division in probabilityOfWinning. You have the right solution to avoiding it---using type Rational = Ratio Integer---but you're applying it too late in the game. By converting toRational after division you've already lost your precision before you converted to Rational.

Try something like this

import Data.Ratio

probabilityOfWinning tree = countWins tree % countGames tree

And then remove the Real type restrictions from countWins and countGames so that they return whole integers instead of floating point numbers. These together will make sure you always use infinite precision math instead of floating point.

Upvotes: 4

Related Questions