0

So I am trying to learn python and wrote a small program to give me the Fibonacci numbers. While I know that they can be defined recursively. I wanted to use the known mathematical formula for Efficiency. My code is very simple:

from math import sqrt
def F(n):
return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))
zahl = int(input("Welche Fibonacci Zahl möchten Sie: "))
print(F(zahl))

When I execute it, it gives me weird rounding Errors, for example for the Input 6 I get

8.000000000000002

instead of the expected 8.0. Does anyone know where this rounding error Comes from and how to avoid it. I was hoping that the Standard sqrt function in the math library was working precise enough! I am using Python 3.5 (32bbit) if that helps.

Dr.H
  • 13
  • 3
  • Floating point arithmetic uses approximations using binary fractions; just round your results for such small inputs. See the duplicates as to how FP errors occur, and how to use the `decimal` module or other flexible-precision fp libraries. – Martijn Pieters Nov 02 '16 at 14:43
  • I don't believe `sqrt()` has any special cases for perfect squares. It probably just uses logarithms or Newton's method to compute the square root. See http://stackoverflow.com/questions/3581528/how-is-the-square-root-function-implemented – Fred Larson Nov 02 '16 at 14:45

0 Answers0