Thread: Loop for 1/3+1/5+1/7...

  1. #1
    Registered User
    Join Date
    Aug 2010
    Posts
    6

    Loop for 1/3+1/5+1/7...

    Trying to set up a loop to count in the following way;
    Want it to count 1/3+1/5+1/7...... for a set number of terms

    So far its just confusing me as to how I could set this up. Is it possible to have a loop count in this way or could it only count using the same value over an over, eg. +2+2+2+2.......

    Thanks

  2. #2
    Registered User
    Join Date
    Aug 2010
    Location
    England
    Posts
    90
    Is this what you want?

    Code:
    double fractioncalc( int count )
    {
    /*
    count is the number of terms 1/1, 1/3,1/5
    count = 1 returns 1
    
    Returns double as result must be FP
    
    Casting used e.g (double) 1 - for clarity - could use literals instead
    */
    
    int i;
    double val = (double) 0;
    
    if( count <= 1 )
             {
               return (double) 1;
              }
    
    for( i = 2; i <= count; i++ )
              {
                val += (double) 1 / ( (double) ( 2*count - 1 ) );
              }
    
    return val;
    }
    Lots of other ways - this should get you started. Sounds like you are just starting. Use this example as a guide, try to do the same thing another way.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    This is how I might write the code along the lines of johnggold's example:
    Code:
    /* Compute 1/3 + 1/5 + 1/7 + ... + 1/(2n+1)
     * Returns result, or 0 if n is non-positive.
     */
    double computeFractionalSum(int n)
    {
        double result = 0.0;
        for (int i = 1; i <= n; ++i)
        {
            result += 1.0 / (2 * n + 1);
        }
        return result;
    }
    In this case the "set number of terms" is straightforward: we're just looping from 1 to n inclusive.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    Aug 2010
    Location
    England
    Posts
    90
    tsk, tsk

    No test for invalid n??. What if n is 0? - loop forever!!!

    And you loop once too many!!!! - requirement is for n - not n+1

    Also ++i - I know you can do this - not usual method - especially when recommending code for a beginner.
    Never re-write code unless the user benefits

  5. #5
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    Quote Originally Posted by johnggold View Post
    tsk, tsk

    No test for invalid n??. What if n is 0? - loop forever!!!

    And you loop once too many!!!! - requirement is for n - not n+1

    Also ++i - I know you can do this - not usual method - especially when recommending code for a beginner.
    It would be interesting to know what code you were looking at to produce such a response. You also might want to fix up your own code.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  6. #6
    Registered User
    Join Date
    Aug 2010
    Location
    England
    Posts
    90
    Well spotted. Should have been :

    Code:
    val += (double) 1 / ( (double) ( 2*i - 1 ) );
    Did fyoung91 spot it?
    Never re-write code unless the user benefits

  7. #7
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Quote Originally Posted by johnggold View Post
    tsk, tsk

    No test for invalid n??. What if n is 0? - loop forever!!!

    And you loop once too many!!!! - requirement is for n - not n+1

    Also ++i - I know you can do this - not usual method - especially when recommending code for a beginner.
    Wow. Amazing post.
    1. What if n is 0? His code won't loop once and return 0 immediately. All input is defined perfectly: 0 for an n <= 0 and otherwise the result. It even says so in the comments.
    2. He doesn't loop once too many. He loops exactly n times.
    3. ++i is actually better practice than i++, usually, unless you have very good reason to use i++. This is because for some classes, ++i will be a lot faster than i++, as it avoids a copy. For integers it usually won't matter, though better use the same standard anyway.

    Actually, there was nothing wrong with his code. Your code is poorly indented (matter of style, though most will agree with me), and has a lot of useless if's.

    Really, the post read like "look how good I am I can write better codez than you". Well, guess what? His code was pretty much perfect, your code isn't, and if you complain about code, at least make sure you know what you complain about. And by the way - you do know you return the wrong result for n = 0, don't you? And that the line casting to double is lousy as well...

  8. #8
    Registered User
    Join Date
    Aug 2010
    Location
    England
    Posts
    90
    I work in a team of six, with six very different styles. We all have tuned beautifiers, which we may use occasionally on very complex code - mostly we read each others style with no problem.

    I first used beautifiers in the 80's - they are freely available - so why make such a big fuss about style - nothing better to talk about I suppose.

    Remember the original enquiry is from a beginner. It is important to be verbose at the beginning, and the explicit checking for invalid values first is good practice, whether or not the main body can or cannot handle it.

    Instead of picking points, why not think about how a beginner must feel with all your sniping - not helpful is it.
    Never re-write code unless the user benefits

  9. #9
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Quote Originally Posted by johnggold View Post
    Instead of picking points, why not think about how a beginner must feel with all your sniping - not helpful is it.
    I can't even be bothered to reply to the rest of your crap that comes from you, but this line stood out to me, in a fairly negative way. "with all my sniping".
    Let me get this straight: you "snipe" (as you call it) at laserlights code, making invalid remarks about it and blaming his style on "++i". Yes, must be very confusing for a beginner. Especially since they are provably wrong. Now I reply, "sniping" at you, to tell you how wrong you were and that your code itself is buggy. This is very helpful for the beginner: he will learn not to use your advise - as it was wrong - and ignore your "sniping".

  10. #10
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    Your style of casting for clarity is also arguably bad, since it opens up your code to some potential pitfalls. At the least, you should use the C++ casting operators to make your intention clear to the compiler.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  11. #11
    Registered User
    Join Date
    Aug 2010
    Location
    England
    Posts
    90
    I passed your email around the office - it got a good laugh.

    I don't have any problem with silverlight - because silverlight thinks positively. The re-written code was a bit short for me, but it was a positive move genuinely attempting to help with the original question.

    Where is your contribution?
    Never re-write code unless the user benefits

  12. #12
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Quote Originally Posted by johnggold View Post
    I passed your email around the office - it got a good laugh.

    I don't have any problem with silverlight - because silverlight thinks positively. The re-written code was a bit short for me, but it was a positive move genuinely attempting to help with the original question.

    Where is your contribution?
    Yes, if you work at an office where six different styles I used, I can imagine them getting a good laugh from that. Did you show them your buggy complaints as well?

    The code was "a bit short on you"? Wait - what? How can too short be a bad thing? Not readable enough - okay, if you're a beginning programmer I can imagine that. But that's not what you said about the code "silverlight" [sic] posted. No, you managed to complain about two bugs that did not exist and a style issue that is usually considered good practice - except perhaps at your office.

    My contribution was to teach you you were wrong, and to let the others know that there were bugs in your post so they shouldn't take it too seriously. The former doesn't seem to be working, though, but I guess that's just because you're too headstrong.

    You sound like a troll, honestly. "I passed your email around the office - it got a good laugh". If there is anything you disagree with in my post, try to be an adult and tell me where you think I went wrong. Unless you can show a more mature site I will not be replying to your posts anymore (unless I forget your name in some other thread, which is fairly likely). Because I know I'm right in this case, and I'm sure that pretty much everyone agrees with my (I bet that "silverlight" [sic] already gave up on you).

    If anyone disagrees with me; please post it here. Tell me why (if you have any good insights in this matter).

  13. #13
    Registered User
    Join Date
    Aug 2010
    Location
    England
    Posts
    90
    You're still not making a contribution to the original question.

    "Because I know I'm right in this case"

    The one thing you learn as you get older is never, never, never say that, because you will get caught.

    My son, who is one of my programmers reminded me that that's what he used to say as a spoilt teenager. He doesn't use it now.

    Be interesting to see whether other contributors agree.
    Never re-write code unless the user benefits

  14. #14
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Quote Originally Posted by johnggold View Post
    You're still not making a contribution to the original question.

    "Because I know I'm right in this case"

    The one thing you learn as you get older is never, never, never say that, because you will get caught.

    My son, who is one of my programmers reminded me that that's what he used to say as a spoilt teenager. He doesn't use it now.

    Be interesting to see whether other contributors agree.
    That's why I said "in this case". Because you are complaining about three points, two of which can easily be proven to be wrong. You want proof? Here:
    [note that I did fix a bug in his code - he used n rather than i in the loop - which wasn't one of the things you complained about though]
    Code:
    #include <iostream>
    
    double computeFractionalSum(int n)
    {
        double result = 0.0;
        for (int i = 1; i <= n; ++i)
        {
            result += 1.0 / (2 * i + 1);
        }
        return result;
    }
    
    int main()
    {
        std::cout << "0: " << computeFractionalSum(0) << std::endl;
        std::cout << "1: " << computeFractionalSum(1) << std::endl;
        std::cout << "2: " << computeFractionalSum(2) << std::endl;
    }
    This produced the output:
    Code:
    0: 0
    1: 0.333333
    2: 0.533333
    Note that:
    1. It does not loop forever for n=0.
    2. It does not loop one too many times, the output was exactly as expected.
    Those were my two main points - in these cases I was right. The third point, "++i", was a matter of style. Though I said nothing wrong there either: for some classes "++i" may be faster than "i++". So why mix the two styles in case you know it's slower and not just use "++i" everywhere.

    Now why not say "I know I'm right in this case", as here I showed you that I am right? It was not a matter of opinion - and I never use that sentence if anything is remotely related to opinion.

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I believe johnggold's objections in post #4 have been addressed. As such...

    Quote Originally Posted by johnggold
    The re-written code was a bit short for me
    I recall a quote along the lines of "I would have written a shorter letter, but I did not have the time". One of the ideas that I attempted to demonstrate in my example was how one could make use of the loop condition to simplify the code. Admittedly, this leads to a slight difference in behaviour: my example returns 0 for a non-positive argument, whereas yours returns 1. Mathematically, I think 0 makes more sense than 1 in this case. On the other hand, it would be easier to modify your example to throw an exception.

    Quote Originally Posted by EVOEx
    His code was pretty much perfect
    Actually, it contains a serious bug which I failed to remove when modifying johnggold's example. pianorain apparently spotted it, and johnggold followed shortly thereafter. The corrected code:
    Code:
    /* Compute 1/3 + 1/5 + 1/7 + ... + 1/(2n+1)
     * Returns result, or 0 if n is non-positive.
     */
    double computeFractionalSum(int n)
    {
        double result = 0.0;
        for (int i = 1; i <= n; ++i)
        {
            result += 1.0 / (2 * i + 1);
        }
        return result;
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Poll event loop
    By rogster001 in forum C++ Programming
    Replies: 2
    Last Post: 09-17-2009, 04:28 AM
  2. need help with a loop
    By Darkw1sh in forum C Programming
    Replies: 19
    Last Post: 09-13-2009, 09:46 PM
  3. funny-looking while loop
    By Aisthesis in forum C++ Programming
    Replies: 3
    Last Post: 08-30-2009, 11:54 PM
  4. nested loop, simple but i'm missing it
    By big_brother in forum C Programming
    Replies: 19
    Last Post: 10-23-2006, 10:21 PM
  5. loop issues
    By kristy in forum C Programming
    Replies: 3
    Last Post: 03-05-2005, 09:14 AM