0

I have to divide here some values, but since it's zero it will give a "ZeroDivisionError". So I coded the following.

if list_actual_revenue[x] != 0.00 or list_actual_revenue[x] != 0:
    print('********************')
    print(list_actual_revenue[x])
    print('********************')
    value_rev = float(list_forecast_revenue[x]) - float(list_actual_revenue[x])
    value_rev = value_rev / float(list_actual_revenue[x])

The error I'm getting is

    value_rev = value_rev / float(list_actual_revenue[x])
ZeroDivisionError: float division by zero

So I decided to print out the values and see what's happening

********************
3120.00
********************
********************
3055.00
********************
********************
11625.00
********************
********************
11937.50
********************
********************
3000.00
********************
********************
3000.00
********************
********************
3000.00
********************
********************
3000.00
********************
********************
3000.00
********************
********************
3000.00
********************
********************
0.00
********************

As you can see the last line is "0.00". My question is: Why is the 0.00 there if the "if statement" has to exclude it?

Robert Grootjen
  • 197
  • 2
  • 13
  • Please provide some sample data so we can [reproduce the problem](https://stackoverflow.com/help/minimal-reproducible-example). Did you save the script after modifying it (just in case)? – a_guest Jan 19 '20 at 18:14
  • Also what data type are you using? Since `print(...)` prints two trailing zeroes it doesn't seem to be `float` since that only has one trailing zero. – a_guest Jan 19 '20 at 18:23
  • Generally speaking you should not compare floats like you have done, because funny behaviour is exhibited with comparison of small numbers, or with numbers that have many decimal places. use list_actual_revenue[x] > 0 and see what happens. – Hayden Eastwood Jan 19 '20 at 18:50

1 Answers1

1

Yeah, I can feel your pain. If you are using floating point, then you should never use "==" or "!=" operators. Instead, try checking if the absolute value of list_actual_revenue[x] > 0.

Or you can try catching the error and then handling the zero case like here: Error python : [ZeroDivisionError: division by zero]

Arutyun Enfendzhyan
  • 1,612
  • 1
  • 12
  • 15
  • Why? Can you provide some evidence for your claim? – a_guest Jan 19 '20 at 18:18
  • https://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples There are tons of materials in google to explain why this is the case. – Arutyun Enfendzhyan Jan 19 '20 at 18:20
  • I'm wondering what this has to do with zero division error and checking for equality with zero. This operation is well defined and doesn't have any accuracy issues. – a_guest Jan 19 '20 at 18:22