0

According to the x value entered using the formula below Write the code of the program that calculates the value of y.

           1
    ---------------
            1
    x + ----------
              1
       x + ------
             1
        x + ---
             2

For example:

If x = 1, y = 0.6000000000000001
If x = 10 y = 0.09901951266867294
If x = 100 y = 0.009999000199950014
If x = -5 y = -0.19258202567760344

My code

x = float(input("x= "))
y = (1.0/(x+(1.0/(x+(1.0/(x+0.5))))))
print(y)

My result

x= 1 y= 0.625
x= 10 y= 0.09901914992993928
x= 100 y= 0.009999000199462694
x= -5 y= -0.19262295081967212

I don't know where i did wrong. Results are so close.

2 Answers2

2

That's because not every number can be represented as floating-point. For example, 0.2 in decimal has finite numbers of digits, but in binary it has not (like 1/3 in decimal). To make very precise operations on floating-point variables, you can use decimal floating point, which works more like a decimal than binary.

Floating-point error: https://en.wikipedia.org/wiki/Floating-point_error_mitigation

Decimal floating-point: https://en.wikipedia.org/wiki/Decimal_floating_point https://docs.python.org/2/library/decimal.html

Alexander Golys
  • 683
  • 8
  • 23
1

in python the interpreter takes approximate for large numbers in (1/1.5) gives out 0.6666666... so add 1 and dividing 1 by it gives 0.6 then after adding 1 then dividing 1 by 1.6 aproximates to 0.625

Sourhead
  • 15
  • 1
  • 5