Python exercise question 019: Sum of score sequences, python019
[Python exercise 019]There is a fractional sequence: 2/1, 3/2, 5/3, 8/5, 13/8, 21/13... to find the sum of the first 20 items of this series.
-----------------------------------------------
This question does not seem to be difficult. The rule is: the numerator of the last score = the numerator + denominator of the previous score, and the denominator of the last score = the numerator of the previous score, the result is returned after 20 cycles. Note: assume that the numerator is a and the denominator is B. Although a = a + B, a has changed to a + B, so when we assign a value to B again, it must be (a + B)-B to be equal to the original denominator B, so when the value is re-assigned, it must be written as a-B. The Code is as follows:
sum = 0a, b = 2, 1for i in range(20): sum = sum + a/b a = a + b b = a - bprint(sum)
The output result is as follows:
32.66026079864164
However, the original question uses scores. After such calculation, it becomes a floating point. Will there be any problems with accuracy? If you want to get it, keep the score more accurate ...... Check and find that the score can only be used from fractions import Fraction. The Code is as follows:
from fractions import Fractionsum = 0a, b = 2, 1for i in range(20): sum = sum + Fraction(a/b) a = a + b b = a - bprint(sum)
The output result is as follows:
73544369181292861/2251799813685248
This score is terrible! Put it in IDLE and calculate it. The result is exactly the same as the floating point number. Okay ......
++
Source: getting started with programming languages: 100 typical examples [Python]