0

I have the code already figured out and have found a way to get around the problem that for k > 6 the largest denominator is very large. But when my code adds up for example

1/float(2) + 1/float(3) + 1/float(7) + 1/float(42)

python says that it is not equal to 1, but it should be. Why does python recognize other sums as being equal to 1 but not this one?

ViKiNG
  • 1,294
  • 2
  • 19
  • 26
user236529
  • 115
  • 1
  • 8
  • Additional info when using fp-math: equality-checks usually follow the approach of [numpy](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.isclose.html). – sascha Oct 17 '17 at 02:45
  • Egyptian fractions are fun. The simple way to work with them in Python is to use the fractions module. – PM 2Ring Oct 17 '17 at 02:51
  • FWIW, here are some lists I've found, which you may find useful in testing your code. These are lists of the given length of minimum highest denominator (with no repeated fractions): 6 [2, 3, 15, 18, 35, 63], 7 [2, 3, 15, 28, 35, 44, 77], 8 [2, 4, 6, 20, 58, 130, 174, 377]. I'm pretty sure 6 & 7 are correct, but I wouldn't be surprised if there's a better solution to 8. – PM 2Ring Oct 17 '17 at 04:55

2 Answers2

2

It is because you are asking for floating point arithmetic, and when the roundoff errors add up, you'll get wrong answers.

Use the https://docs.python.org/3/library/fractions.html module to get real fractions and roundoff issues should disappear for you.

btilly
  • 43,296
  • 3
  • 59
  • 88
0

You need to be extremely careful when hard-comparing any decimal values. Computer don't provide unlimited precision, thus it could be that your argument adds up to something like 0.99999998 instead of 1. Then the comparison might fail.

Thus you should always compare corresponding to an allowed difference of delta, like 1 - 0.99999998 < delta where delta = 0.0001 or something like that.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82