1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Reusable formula for decrementing denominator

  1. Sep 10, 2011 #1
    I am currently working on computer program that has to find the sum of during looping:

    1 + 1/2 + 1/3 + 1/4 + etc.

    So the loop looks something like this:

    sum = 1;
    counter = 2;

    while(...){
    sum = sum + (1/counter);
    counter = counter +1;
    }

    My general question however is purely mathematical.

    I am currently using a basic counter variable to keep track of what the next denominator value will be, but I was hoping there was some formula I could be used to go from: 1/2 to 1/3, then 1/3 to 1/4. I am unable to find a consistent relationship between each value and the next in order to simplify my code. Any suggestions would be greatly appreciated.
     
  2. jcsd
  3. Sep 10, 2011 #2
    The relationship is nonlinear -- you can't find a common difference or ratio between each pair of adjacent terms. The relationship is as follows: if the term in question is [itex]1 \over n[/itex], then the following term will be [itex]1 \over n + 1[/itex]. It's not really like you can add or multiply some constant to get the next term in the sequence.
     
  4. Sep 10, 2011 #3
    What he said. Looks like you're using JavaScript or similar, so you can sacrifice some readability and shorten it to
    Code (Text):
    sum = 1;
    counter = 2;

    while(...){
    sum = sum + (1/counter++);
    }
    The trailing ++ tells the compiler to add 1 to counter after the expression has been evaluated. That's about as simple as this code can get.

    Fred
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Reusable formula for decrementing denominator
Loading...