(Term0 + Term1 - Term2 + Term3) How can I do the alternating plus minus?

This is a discussion on (Term0 + Term1 - Term2 + Term3) How can I do the alternating plus minus? within the C Programming forums, part of the General Programming Boards category; I am working on a problem involving Taylor's Series of cosine x and sine x. (cosx = 1 - (x^2/2!) ...

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    1

    Unhappy (Term0 + Term1 - Term2 + Term3) How can I do the alternating plus minus?

    I am working on a problem involving Taylor's Series of cosine x and sine x. (cosx = 1 - (x^2/2!) + (x^4/4!) - ...)
    My only problem is how I can do the alternating plus minus on each term. This is the code I currently have in which I can't still figure out if it is right or wrong.

    double cosine(double x)
    {
    int n, ctr;
    double cos;

    cos = 0;
    n = 2*NUMBER_OF_TERMS;
    ctr = NUMBER_OF_TERMS;
    while(ctr > 0)
    {
    ctr--;
    cos = cos + (RaiseTo(x, n)/factorial(n));
    cos *= -1;
    n -= 2;
    }
    return cos;
    }

    *Note: We were only allowed to use stdio.h as the header file.

  2. #2
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,183
    Code:
    if (term % 2 == 0) {
    x *= -1;
    }
    or, if you want to avoid a branch
    Code:
    double sign = 1;
    while (...) {
         x *= sign;
         sign *= -1;
    }
    Not sure which one would be faster.

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,012
    x *= -1 is also the same as x = -x. The latter would probably be faster in terms of instructions, but a good compiler will probably optimize it.
    However, be sure to read this: << !! Posting Code? Read this First !! >>
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21