C evaluating a recursive sequence - expected expression error -
i'm trying code recursive sequence values n = 60. know x0 = 1.
xn+1 = 2^(n+1) * (sqrt( 1 + 2^-n*xn) - 1)
so far have
int main () { // first term x0 = 1 double xn = 1; double x; double squareroot = 1 + (pow(2, -x) * xn); (x = 1; x <= 60; x++) { double xn = pow(2, x) * double sqrt(squareroot) - 1); printf("%f\n", xn); } }
but expected expression error on line there double sqrt.
as mentioned in other answers, code had syntax errors in line:
double xn = pow(2, x) * double sqrt(squareroot) - 1);
here parenthesis not balanced have 1 more )
(
. in addition cannot place double
did (it not needed sqrt
returns double
)
below placed code comments of how interpreted equation along notes on found ambiguous how written:
#include <math.h> #include <stdio.h> int main() { int n; // mentioned x0 1.0 , variable updated initialized 1.0 double x = 1.0; // goal: xn+1 = 2^(n+1) * (sqrt( 1 + 2^-n*xn) - 1) // notes: // - named xn x separate updated variable iteration variable // - interpreted "2^-n*xn" "pow(2.0, -n) * x" (rather "pow(2.0, -n * x)") (n = 1; n < 60; n++) { // term a: 2^(n+1) double terma = pow(2.0, n + 1.0); // term b: (sqrt( 1 + 2^-n*xn) - 1) // note involves updated variable, must in loop double termb = sqrt(1.0 + pow(2.0, -n) * x) - 1.0; // update x: terma * termb x = terma * termb; printf("%f\n", x); } return 0; }
added clarity:
int main() { int n; double x = 1.0; (n = 1; n < 60; n++) { // these temporary values assigned every iteration // note unlike code "pow(2.0, -n) * x" evaluated // every iteration , updates reflect desired equation // in code used "squareroot" did not update every iteration double terma = pow(2.0, n + 1.0); double termb = sqrt(1.0 + pow(2.0, -n) * x) - 1.0; // updates value of "x" every iteration // "x" corresponds called "xn" in equation x = terma * termb; printf("%f\n", x); } return 0; }
Comments
Post a Comment