0

Why does the following code return the following output?

def z(x, y):
    return (x + 2*y + 1)**2

delta = 0.1
x_derivative = (z(delta, 0) - z(0, 0)) / delta
print(x_derivative)

Output: 2.100000000000002

If my maths is correct, it should just be 2.1.

This has probably be asked before, but I don't know the right terms to search for.

Ewan Brown
  • 143
  • 1
  • 9
  • 1
    There are infinitely many real numbers that can't be represented with the finite set of floating point numbers in any real computer. `2.1` is an example of a number with no perfect representation in the IEEE binary format used by most modern processors. What was printed is the closest you'll get. – Gene Feb 11 '20 at 01:31

1 Answers1

0

This is due to the representation of floating point numbers internally that causes errors of precisions like that one.

0.1 in binary has an infinite representation (much like 1/3 in base 10), so that's why you get that deviation.

Educorreia
  • 375
  • 5
  • 21
  • Ah thanks for the info. Is there a simple way to have a variable as just 2.1? I don't want to cut down the string output, I actually want the variable to be exactly 2.1. I'm new to python and I'm coming from a Java background where the intricacies of the Float object is hidden from me :P – Ewan Brown Feb 11 '20 at 01:41
  • 1
    @EwanBrown Python's `float` is basically the same as `double` in Java. They are both double-precision IEEE 754 floating-point number types, so 2.1 is not exactly representable as a `double` in Java either. – kaya3 Feb 11 '20 at 03:49