Continued Fraction This assignment involves computing continued fractions, and c
ID: 662314 • Letter: C
Question
Continued Fraction This assignment involves computing continued fractions, and contains three parts. The general form of a continued fraction is: A finite continued fraction s an expression of the form where a0 is an integer, all other a, are positive integers, and n is a non-negative integer. We can specify a continued fraction by an array of integers containing the values a0 .. a... 1. Write a function that takes an array of integers as specified above (and ending with a -1) and returns the value of the fraction as a double. 2. Write a function that takes an array of integers as specified above (and ending with a -1). Your function will represent the value of the continued fraction as a regular'' fraction, p/q, in lowest terms. We are looking for the result of doing the fractional arithmetic and keeping everything in integers as we work our way through. The function returns a 2-element integer array, y, with v[0] = p and v[1] = q. 3. Write recursive functions that, given the above representation of a continued fraction, returns p and q such that p/q represent the value of the continued fraction as a ''regular'' fraction in lowest terms, as in question 2 above.Explanation / Answer
/* calculate approximations for continued fractions */
#include <stdio.h>
/* kind of function that returns a series of coefficients */
typedef double (*coeff_func)(unsigned n);
/* calculates the specified number of expansions of the continued fraction
* described by the coefficient series f_a and f_b */
double calc(coeff_func f_a, coeff_func f_b, unsigned expansions)
{
double a, b, r;
a = b = r = 0.0;
unsigned i;
for (i = expansions; i > 0; i--) {
a = f_a(i);
b = f_b(i);
r = b / (a + r);
}
a = f_a(0);
return a + r;
}
/* series for sqrt(2) */
double sqrt2_a(unsigned n)
{
return n ? 2.0 : 1.0;
}
double sqrt2_b(unsigned n)
{
return 1.0;
}
/* series for the napier constant */
double napier_a(unsigned n)
{
return n ? n : 2.0;
}
double napier_b(unsigned n)
{
return n > 1.0 ? n - 1.0 : 1.0;
}
/* series for pi */
double pi_a(unsigned n)
{
return n ? 6.0 : 3.0;
}
double pi_b(unsigned n)
{
double c = 2.0 * n - 1.0;
return c * c;
}
int main(void)
{
double sqrt2, napier, pi;
sqrt2 = calc(sqrt2_a, sqrt2_b, 1000);
napier = calc(napier_a, napier_b, 1000);
pi = calc(pi_a, pi_b, 1000);
printf("%12.10g %12.10g %12.10g ", sqrt2, napier, pi);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.