I would like to calculate the sum of reciprocals of a list of integers (and see if it is larger or equal to 1):
I want to work with integers to avoid floating-point rounding issues. To do so, I want to work it out like this:
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With