Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate sum of reciprocals with integers?

I would like to calculate the sum of reciprocals of a list of integers (and see if it is larger or equal to 1):

enter image description here

I want to work with integers to avoid floating-point rounding issues. To do so, I want to work it out like this:

enter image description here

I have done this:

import numpy as np

my_list = [2, 3, 5, 7]
numerator = 0
for i in range(len(my_list)):
    numerator += np.product(my_list[:i] + my_list[i+1 :])
denominator = np.product(my_list)
result = numerator>=denominator

but I feel like there should be a one-liner for that. Is there a function to calculate the sum of reciprocals as fractions? Or perhaps a function to calculate the numerator from a list?

like image 574
Rémi Baudoux Avatar asked Sep 03 '25 03:09

Rémi Baudoux


1 Answers

The Fraction type can do this easily and exactly:

>>> from fractions import Fraction
>>> bottoms = [2, 3, 5, 7]
>>> total = sum(Fraction(1, d) for d in bottoms)
>>> total
Fraction(247, 210)
>>> total > 1
True
like image 192
Tim Peters Avatar answered Sep 04 '25 18:09

Tim Peters