0

my code (shown below) is producing a result that was not as expected and I don't understand why

InningsPitched = [228,205,196,194,181,164]
EarnedRuns =  [58,74,49,67,59,79]
Pitcher = ["Sandy Alcantara","Aaron Nola","Alek Manoah","Yu Darvish","Joe Musgrove","Corey Kluber"]
i = 0

for era in InningsPitched:
    print(Pitcher[i],9 * EarnedRuns[i] // InningsPitched[i] + 9 * EarnedRuns[i] % InningsPitched[i] / InningsPitched[i] * 100 // 1 / 100)
    i=i+1

Sandy Alcantara 2.2800000000000002
Aaron Nola 3.24
Alek Manoah 2.25
Yu Darvish 3.1
Joe Musgrove 2.93
Corey Kluber 4.33

I was expecting Sandy Alcantara to have an ERA of 2.28 not 2.2800000000000002

Ben Grossmann
  • 4,387
  • 1
  • 12
  • 16
  • 5
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic](//docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) Also [Is floating point math broken?](https://stackoverflow.com/q/588004/843953) – Pranav Hosangadi Mar 14 '23 at 19:50
  • 1
    Here's a simpler example: try `print(.2+.1)` – Ben Grossmann Mar 14 '23 at 19:52
  • 3
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) see also for a fix to the display : https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points – JonSG Mar 14 '23 at 19:53
  • `9 * EarnedRuns[i] / InningsPitched[i]` would work just as well without all the ineffective attempts to (I assume) avoid floating-point inaccuracy. – chepner Mar 14 '23 at 19:57
  • Unrelated, `for pitcher, er, innings in zip(Pitcher, EarnedRuns, InningsPitched): ...` would make this much simpler. – chepner Mar 14 '23 at 19:59
  • 1
    @JonSG Thank you this helped so much, I am learning python and have not run into this yet and I was so confused – Jameswoody0802 Mar 14 '23 at 20:05

0 Answers0