Continued Fractions Python [closed]

2024/4/15 2:10:06

I am new to Python and was asked to create a program that would take an input as a non-negative integer n and then compute an approximation for the value of e using the first n + 1 terms of the continued fraction:

I have attempted to decipher the question but can't exactly understand everything it is asking. I am not looking for an exact answer but hopefully an example to help me on my way.

This is the exact question
Below is a code I have done with continued fractions before.

import math
# Get x from user
x = float(input("Enter x = "))# Calculate initial variables and print
a0 = x//1
r0 = x-a0
print("a0 =", a0, "\tr0 =", r0)# Calculate ai and ri for i = 1,2,3 and print resultsa1 = 1/r0//1
r1 = 1/r0 - a1
print("a1 =", a1, "\tr1 =", r1)a2 = 1/r1//1
r2 = 1/r1 - a2
print("a2 =", a2, "\tr2 =", r2)a3 = 1/r2//1
r3 = 1/r2 - a3
print("a3 =", a3, "\tr3 =", r3)

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 expansionSee see by PM 2Ring 2016.03.18
'''from __future__ import print_function, division
import sysdef contfrac_to_frac(seq):''' Convert the simple continued fraction in `seq` into a fraction, num / den'''num, den = 1, 0for u in reversed(seq):num, den = den + num*u, numreturn num, dendef 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] += 1return seqdef main():# Get the the number of terms, less onen = int(sys.argv[1]) if len(sys.argv) > 1 else 11if n < 0:print('Argument must be >= 0')exit()n += 1seq = 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()


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, 0for u in seq:n, d, num, den = num, den, num*u + n, den*u + dreturn num, den

Related Q&A

Spark: equivelant of zipwithindex in dataframe

Assuming I am having the following dataframe:dummy_data = [(a,1),(b,25),(c,3),(d,8),(e,1)] df = sc.parallelize(dummy_data).toDF([letter,number])And i want to create the following dataframe: [(a,0),(b,2…

How to find list comprehension in python code

I want to find a list comprehension in python source code, for that I tried to use Pygments, but it didnt find the way to do that. To be more specific, I want to do a function that recognize all the po…

Save XLSX file to a specified location using OpenPyXL

Im having an issue saving my file to a certain location on my Raspberry PI (Raspbian) computer. Im wanting the XLSX file to be saved directly to my desktop rather than the folder holding the Python Sc…

Pandas read csv dateint columns to datetime

Im new to both StackOverflow and pandas. I am trying to read in a large CSV file with stock market bin data in the following format:date,time,open,high,low,close,volume,splits,earnings,dividends,sym 20…

Pydantic - Dynamically create a model with multiple base classes?

From the pydantic docs I understand this: import pydanticclass User(pydantic.BaseModel):id: intname: strclass Student(pydantic.BaseModel):semester: int# this works as expected class Student_User(User, …

Handling nested elements with Python lxml

Given the simple XML data below:<book><title>My First Book</title><abstract><para>First paragraph of the abstract</para><para>Second paragraph of the abstract&…

Easiest way to plot data on country map with python

Could not delete question. Please refer to question: Shade states of a country according to dictionary values with Basemap I want to plot data (number of sick people for a certain year) on each state o…

How to resize QMainWindow after removing all DockWidgets?

I’m trying to make an application consisting of a QMainWindow, the central widget of which is a QToolBar (it may not be usual, but for my purpose the toolbar’s well suited). Docks are allowed below o…

Python: sorting a list by column [duplicate]

This question already has answers here:How to sort a list/tuple of lists/tuples by the element at a given index(11 answers)Closed 8 years ago.How can I sort a list-of-lists by "column", i.e. …

How to make setuptools clone git dependencies recursively?

I want to let setuptools install Phoenix in my project and thus addedsetup(...dependency_links = ["git+"],install_requires = ["Phoenix…