-5

enter image description here

I tried to use this code to solve the question in the picture but I can't solve it, I'd be happy to help.

how can I fix the code that works for the question in the picture? thanks.

#include

void main() {
    int n, i;
    double sum, x, last;
    do {
        printf("Enter an positive number: ");
        scanf("%d", & n);
    } while (n<0);
    printf("Please enter x: ");
    scanf("%lf", & x);
    sum = last = x;
    for (i = 1; i<= n; i++) {
        last = last * (-1) * ((x * x) / ((2 * i - 1) * (2 * i)));
        sum = sum + last;
    }
    printf("S = %lf\n", sum);
}
Bohao LI
  • 2,123
  • 2
  • 18
  • 24
ohade94
  • 1
  • 2
  • 1
    I'm curious what the equation is. A Taylor series for something? – Galen Apr 16 '20 at 20:29
  • 1
    @Galen Looks like it could be Taylor approximations for 2*(cosh(x-1)-1)/(x-1). – aschepler Apr 16 '20 at 20:54
  • You should be able to derive each term from the previous term, avoiding high powers and factorials. The downside is that the [inaccuracy of floating point types](https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) will propagate. – Weather Vane Apr 16 '20 at 20:58
  • Your code has a `* (-1)` which doesn't correspond to the equation, and I don't see anything in the code accounting for the *2, *3, *4, *5, ... (n+1) from the denominators. – aschepler Apr 16 '20 at 20:58
  • 1
    Or is the code the solution to some similar problem, and needs to be modified to match the new formula? If so, do you understand how the code calculates the other formula? – aschepler Apr 16 '20 at 21:02
  • 1
    @WeatherVane The inaccuracy should be rather good here for most inputs, since all the addends have the same sign, and the terms will quickly decrease in magnitude. – aschepler Apr 16 '20 at 21:14

1 Answers1

0

As mentioned in the comments, you are using the wrong quotient. Also, a closed expression for the value of the series is available.

From the last term of the formula you can read off the general form of the terms

    a[k] = (x-1)^(2k+1) / ( (2k+1)! * (k+1) ),  k = 0,..., n

The quotient of two such adjacent terms is

    a[k]/a[k-1] = (x-1)^2 / ( (2k+1)*2(k+1) )

so that the modified code computing your sum is

#include<math.h>
#include<stdio.h>

void main() {
    int n, i;
    double sum, x,x1s last;
    do {
        printf("Enter an positive number: ");
        scanf("%d", & n);
    } while (n<0);
    printf("Please enter x: ");
    scanf("%lf", & x);
    sum = last = x-1;
    x1s = last*last;
    for (i = 1; i<= n; i++) {
        last = last * (x1s / ((2*i+1) * 2 * (i+1)));
        sum = sum + last;
    }
    printf("S = %20.15lf,  S_infty = %20.15lf\n", sum, 2*(cosh(x-1)-1)/(x-1));
}
Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51