0

I wrote this function to avoir typing on a calculator and make my homework faster but something very strange happened :

def G(x):
  return 1 - x ** 2 - (1-x) ** 2

G(1/5) gives 0.31999999999999984

But it is clearly 25/25 - 1/25 - 16/25 with is 8/25 = 0.32

1 Answers1

-1

You can use the decimal module as a workaround.

The decimal module provides support for fast correctly-rounded decimal floating point arithmetic. It offers several advantages over the float datatype.

from decimal import Decimal;

print(float(G(Decimal(1)/Decimal(5))))
0.32
Corralien
  • 109,409
  • 8
  • 28
  • 52