avatar Bite 325. Floating point arithmetic

This Bite introduces you to a few issues associated with doing floating point arithmetic: the numbers that you 'see on screen', and the arithmetic that you were taught at school, might not correspond with how those numbers are represented internally on your machine.

These issues often come to the fore when sending and receiving JSON-encoded numbers between systems, having to convert numbers between their string and floating point representations, and performing arithmetic and rounding operations on those numbers.

Given the following JSON-encoded string containing a number of floating point values:

"[0.1, 0.2, 0.3, 0.005, 0.005, 2.67]"

...complete function calc_sums that produces a sequence of strings that, when read, will recite the calculation and provide the result of summing each adjacent pair of numbers. For example, the output produced should be:

The sum of 0.1 and 0.2, rounded to two decimal places, is 0.30.
The sum of 0.2 and 0.3, rounded to two decimal places, is 0.50.

...and so on until all five pairs of numbers have been processed. The summed values should also be rounded to two decimal places, with ties rounded up (e.g. 0.305 is rounded up to 0.31).

Have a look at this tutorial in the Python standard documentation for an introduction to floating point arithmetic if you get stuck.

Have fun and keep calm and code in Python!

Login and get coding
go back Intermediate level
Bitecoin 3X

20 out of 24 users completed this Bite.
Will you be Pythonista #21 to crack this Bite?
Resolution time: ~49 min. (avg. submissions of 5-240 min.)

We use Python 3.8