写代码求分数序列: 求出这个数列2/1,-3/2,5/3,-13/5,-21/13的前20项之和
时间: 2023-05-28 13:01:09 浏览: 109
stern-brocot:Stern-Brocot 序列中的数分布
# 定义分数类
class Fraction:
def __init__(self, numerator, denominator):
if denominator == 0:
raise ZeroDivisionError("Denominator cannot be zero.")
if denominator < 0:
numerator = -numerator
denominator = -denominator
self.numerator = numerator
self.denominator = denominator
def __add__(self, other):
numerator = self.numerator * other.denominator + self.denominator * other.numerator
denominator = self.denominator * other.denominator
return Fraction(numerator, denominator)
def __str__(self):
return str(self.numerator) + "/" + str(self.denominator)
# 求分数序列
def fraction_sequence(n):
fractions = [Fraction(2, 1)]
for i in range(n - 1):
if i % 2 == 0:
numerator = -3 * fractions[-1].numerator - 2 * fractions[-1].denominator
denominator = 2 * fractions[-1].numerator + fractions[-1].denominator
else:
numerator = -13 * fractions[-1].numerator - 21* fractions[-1].denominator
denominator = 5 * fractions[-1].numerator + 8 * fractions[-1].denominator
fractions.append(Fraction(numerator, denominator))
return fractions
# 测试
if __name__ == '__main__':
fractions = fraction_sequence(20)
sum = Fraction(0, 1)
for frac in fractions:
sum += frac
print(frac)
print("Sum:", sum)
阅读全文