Hướng dẫn continued fractions in python

Without further information, it's probably a Good Idea™ to use the simple continued fraction expansion of e, as shown in Wikipedia:

e = [2; 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10, 1, 1, 12, 1, 1, ...]

This sequence can easily be created using a simple list comprehension.

To evaluate a simple continued fraction expansion we can process the list in reversed order.

The following code will work on Python 2 or Python 3.

#!/usr/bin/env python

''' Calculate e using its simple continued fraction expansion

    See //stackoverflow.com/q/36077810/4014959

    Also see
    //en.wikipedia.org/wiki/Continued_fraction#Regular_patterns_in_continued_fractions

    Written by PM 2Ring 2016.03.18
'''

from __future__ import print_function, division
import sys

def contfrac_to_frac[seq]:
    ''' Convert the simple continued fraction in `seq` 
        into a fraction, num / den
    '''
    num, den = 1, 0
    for u in reversed[seq]:
        num, den = den + num*u, num
    return num, den

def e_cont_frac[n]:
    ''' Build `n` terms of the simple continued fraction expansion of e
        `n` must be a positive integer
    '''
    seq = [2 * [i+1] // 3 if i%3 == 2 else 1 for i in range[n]]
    seq[0] += 1
    return seq

def main[]:
    # Get the the number of terms, less one
    n = int[sys.argv[1]] if len[sys.argv] > 1 else 11
    if n < 0:
        print['Argument must be >= 0']
        exit[]

    n += 1
    seq = e_cont_frac[n]
    num, den = contfrac_to_frac[seq]

    print['Terms =', n]
    print['Continued fraction:', seq]
    print['Fraction: {0} / {1}'.format[num, den]]
    print['Float {0:0.15f}'.format[num / den]]

if __name__ == '__main__':
    main[]

output

Terms = 12
Continued fraction: [2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8]
Fraction: 23225 / 8544
Float 2.718281835205993

Pass the program an argument of 20 to get the best approximation possible using Python floats: 2.718281828459045

As Rory Daulton [& Wikipedia] mention, we don't need to reverse the continued fraction list. We can process it in the forward direction, but we need 2 more variables because we need to track 2 generations of numerators and denominators. Here's a version of contfrac_to_frac which does that.

def contfrac_to_frac[seq]:
    ''' Convert the simple continued fraction in `seq`
        into a fraction, num / den
    '''
    n, d, num, den = 0, 1, 1, 0
    for u in seq:
        n, d, num, den = num, den, num*u + n, den*u + d
    return num, den

Algorithm: Continued Fraction [Python]

Known time/storage complexity and/or correctness

The continued fraction of a real number $x\in\mathbb R$ can be computed by the following algorithm.1

1 Because floating point arithmetic IEEE-754 “double precision”, python doubles contain 53 bits of precision. Therefore, the algorithm not always computes the write values of the continued fraction. The algorithm also limits the computation to 20 values of the continued fraction, since some continued fractions are not finite.

Short Name

$\operatorname{contFrac}$

Input Parameters

real number $x\in\mathbb R$

Output Parameters

continued fraction $[x_0;x_1,x_2,\ldots]$

Python Code

import math

def contFrac[x, k]:
    cf = []
    q = math.floor[x]
    cf.append[q]
    x = x - q
    i = 0
    while x != 0 and i < k:
        q = math.floor[1 / x]
        cf.append[q]
        x = 1 / x - q
        i = i + 1
    return cf

# Usage
print[contFrac[math.sqrt[2]]]

# will output 
# [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]

|
|
|
| created: 2019-06-23 17:31:32 | modified: 2019-06-23 19:06:33 | by: bookofproofs | references: [1357], [8186]

1.Proof: [related to "Continued Fraction [Python]"]

Source code: Lib/fractions.py

The fractions module provides support for rational number arithmetic.

A Fraction instance can be constructed from a pair of integers, from another rational number, or from a string.

class fractions.Fraction[numerator=0, denominator=1]¶ class fractions.Fraction[other_fraction] class fractions.Fraction[float] class fractions.Fraction[decimal] class fractions.Fraction[string]

The first version requires that numerator and denominator are instances of numbers.Rational and returns a new Fraction instance with value numerator/denominator. If denominator is 0, it raises a ZeroDivisionError. The second version requires that other_fraction is an instance of numbers.Rational and returns a Fraction instance with the same value. The next two versions accept either a float or a decimal.Decimal instance, and return a Fraction instance with exactly the same value. Note that due to the usual issues with binary floating-point [see Floating Point Arithmetic: Issues and Limitations], the argument to Fraction[1.1] is not exactly equal to 11/10, and so Fraction[1.1] does not return Fraction[11, 10] as one might expect. [But see the documentation for the limit_denominator[] method below.] The last version of the constructor expects a string or unicode instance. The usual form for this instance is:

[sign] numerator ['/' denominator]

where the optional sign may be either ‘+’ or ‘-’ and numerator and denominator [if present] are strings of decimal digits. In addition, any string that represents a finite value and is accepted by the float constructor is also accepted by the Fraction constructor. In either form the input string may also have leading and/or trailing whitespace. Here are some examples:

>>> from fractions import Fraction
>>> Fraction[16, -10]
Fraction[-8, 5]
>>> Fraction[123]
Fraction[123, 1]
>>> Fraction[]
Fraction[0, 1]
>>> Fraction['3/7']
Fraction[3, 7]
>>> Fraction[' -3/7 ']
Fraction[-3, 7]
>>> Fraction['1.414213 \t\n']
Fraction[1414213, 1000000]
>>> Fraction['-.125']
Fraction[-1, 8]
>>> Fraction['7e-6']
Fraction[7, 1000000]
>>> Fraction[2.25]
Fraction[9, 4]
>>> Fraction[1.1]
Fraction[2476979795053773, 2251799813685248]
>>> from decimal import Decimal
>>> Fraction[Decimal['1.1']]
Fraction[11, 10]

The Fraction class inherits from the abstract base class numbers.Rational, and implements all of the methods and operations from that class. Fraction instances are hashable, and should be treated as immutable. In addition, Fraction has the following properties and methods:

Changed in version 3.9: The math.gcd[] function is now used to normalize the numerator and denominator. math.gcd[] always return a int type. Previously, the GCD type depended on numerator and denominator.

numerator

Numerator of the Fraction in lowest term.

denominator

Denominator of the Fraction in lowest term.

as_integer_ratio[]

Return a tuple of two integers, whose ratio is equal to the Fraction and with a positive denominator.

New in version 3.8.

classmethod from_float[flt]

Alternative constructor which only accepts instances of float or numbers.Integral. Beware that Fraction.from_float[0.3] is not the same value as Fraction[3, 10].

Note

From Python 3.2 onwards, you can also construct a Fraction instance directly from a float.

classmethod from_decimal[dec]

Alternative constructor which only accepts instances of decimal.Decimal or numbers.Integral.

limit_denominator[max_denominator=1000000]

Finds and returns the closest Fraction to self that has denominator at most max_denominator. This method is useful for finding rational approximations to a given floating-point number:

>>> from fractions import Fraction
>>> Fraction['3.1415926535897932'].limit_denominator[1000]
Fraction[355, 113]

or for recovering a rational number that’s represented as a float:

>>> from math import pi, cos
>>> Fraction[cos[pi/3]]
Fraction[4503599627370497, 9007199254740992]
>>> Fraction[cos[pi/3]].limit_denominator[]
Fraction[1, 2]
>>> Fraction[1.1].limit_denominator[]
Fraction[11, 10]
__floor__[]

Returns the greatest int >> from math import floor >>> floor[Fraction[355, 113]] 3 __ceil__[]

Returns the least int >= self. This method can also be accessed through the math.ceil[] function.

__round__[]__round__[ndigits]

The first version returns the nearest int to self, rounding half to even. The second version rounds self to the nearest multiple of Fraction[1, 10**ndigits] [logically, if ndigits is negative], again rounding half toward even. This method can also be accessed through the round[] function.

See also

Module numbers

The abstract base classes making up the numeric tower.

How do you round in math in Python?

Python has a built-in round[] function that takes two numeric arguments, n and ndigits , and returns the number n rounded to ndigits . The ndigits argument defaults to zero, so leaving it out results in a number rounded to an integer.

Do fractions work in Python?

In Python the Fraction module supports rational number arithmetic. Using this module, we can create fractions from integers, floats, decimal and from some other numeric values and strings. There is a concept of Fraction Instance. It is formed by a pair of integers as numerator and denominator.

How do you round a decimal number in Python?

Python round[] Function The round[] function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals. The default number of decimals is 0, meaning that the function will return the nearest integer.

Chủ Đề