Python exercise question 019: Sum of score sequences, python019

Source: Internet
Author: User

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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.