+ 1

What is a standard approach to deal with float precision in python?

for example at the Paint costs challenge from codecoach, I did a workaround that worked. It's not efficient nor best programming practice. Moreover I did that only because the tests don't pass with 2 as input. At this post I found some useful information about it https://realpython.com/JUMP_LINK__&&__python__&&__JUMP_LINK-rounding/ I found this an interesting theme to raise. Sorry if it was a repetitive and or bad formulated question, I'm just a beginner. Sample code: from math import ceil nr_color = 2 # nr_color = int(input()) price_per_color = 5 price_fix = 40 tax = 0.1 price = price_per_color * nr_color + price_fix print(price) # 50 price = price * (1+tax) print(price) # float precision issue # 55.00000000000001 # without workaround price1 = ceil(price) print('without workaround: ', price1) # 56 # workaround price2 = round(price, 3) price2 = ceil(price2) print('with workaround: ', price2) # 55

20th Jul 2020, 1:03 AM
Vinícius Rios
1 Respuesta
0
That's not really an issue and you solved it exact the same way as I've seen it trillion times, because it is not a workaround but the correct way to deal with float. Therefore many languages provide "higher" datatypes, like e.g. the "BigDecimal" in Java. Not sure, if there's an equivalent type in python.
20th Jul 2020, 1:36 PM
Sandra Meyer
Sandra Meyer - avatar