0

The sum to infinity of the following series is to be found:

1  1/2  1/3  1/4  1/5 ...

According to the explanation of a certain scientist, infinity is that point beyond which any point is non existent, i.e., inf + x = inf or inf ~ (inf + x) = 0. So, based on this theory, the following algorithm was used:

float sum=0.0;
for(int i=0;;i++){
    if((sum+(1.0/i))==sum)
    break;
    sum+=(1.0/i);
}
/* print the value of sum */

The algorithm was run in C and JAVA and both gave the output as inf. The print statements written in C and Java respectively are

printf("%6f",sum);  

System.out.println(sum);  

EDIT: The code written earlier (in the question) had a mistake because I typed it, didn't copy-paste. Sorry for that. That being solved, here's the code I'd base my question upon:

float sum=0.0;
for(int i=1;;i++){
    if((sum+ (1.0/i))==sum)
    break;
    sum+=(1.0/i);
}
/*print the value of sum*/

A friend of mine said he got the output as a finite fractional number in C. But in my case, the program never terminated, both in C and Java(This output was got from the new edited code posted above. Do not consider the previous faulty code and it's output which was "INF".) My question is, is this algorithm acceptable? And if yes, then I'd like to know the possible of cause different outputs in C. Thanks.

  • 10
    You're adding 1/0 (which is infinity) in the very first iteration... change `i` to start at 1 and you'll get different results... – Jon Skeet Mar 08 '16 at 07:20
  • It will terminate when the int i overflows and becomes 0, whereby you will add 1/0 which is infinity. – nitegazer2003 Mar 08 '16 at 07:22
  • 2
    @DawidPi: Don't most implementations of C use IEEE-754, which *does* have a representation of infinity? (And it's not just "Java's max double number" - it's "the IEEE-754 representation of infinity. The maximum representable finite `double` is a very different number.) – Jon Skeet Mar 08 '16 at 07:22
  • @AkiSuihkonen it stops in the if statement, when i is so large, that after addidition 1.0/i to sum it does not change it's value - flot precision is too small – DawidPi Mar 08 '16 at 07:22
  • Actually, there's a subtlety here, at least in Java - `sum+(1.0/i) == sum` is performed using `double` arithmetic, whereas `sum += (1.0/i)` performs the addition using `double` arithmetic *but then converts the result back to `float`*. So I wouldn't be surprised if it really didn't terminate... but declaring `sum` as a `double` instead, it would (if `i` overflowing weren't an issue...) – Jon Skeet Mar 08 '16 at 07:25
  • 2
    That being said, mathematically speaking, sum of 1/n from 1 to n is tends to be proportional to the natural log of n, so within the bounds of a positive int, you're more likely to get an answer thats in the area of ln(Integer.MAX_VALUE) – nitegazer2003 Mar 08 '16 at 07:25
  • @JonSkeet yes I was wrong. sorry. – DawidPi Mar 08 '16 at 07:26
  • But still in fact what you are doing is undefined behavior in C, because of division by zero in first iteration. – DawidPi Mar 08 '16 at 07:27
  • I've edited the question. Please check. –  Mar 08 '16 at 07:54
  • I rolled the changes back You had completely changed the question. – juanchopanza Mar 08 '16 at 07:54
  • This sum doesn't converge. – Frederick Cheung Mar 08 '16 at 07:54
  • Did you even try to compile/run this code? Whee did you get it from? – Martin James Mar 08 '16 at 08:50
  • 'A friend of mine said he got the output as a finite fractional number' - what did YOU get when you tried it? – Martin James Mar 08 '16 at 08:51
  • You are making this up as you go along:( – Martin James Mar 08 '16 at 08:52
  • Ignoring the mistake in the code, i.e., considering I started from ´i=1´, I didn't get an output. The program didn't terminate by itself. The loop became infinite. –  Mar 08 '16 at 08:53
  • I ain't making anything up. I just made a small mistake in the beginning. And I donno why I cannot delete the question. –  Mar 08 '16 at 08:57
  • A small mistake? How is it possible for a copy/paste from the code that you tried to change '1' to '0'? – Martin James Mar 08 '16 at 08:59
  • Stephen C answered your question and got 5 upvotes for it, (well OK, he answered the edited version of your question that mentioned INF). Why would you want him to lose those 5 upvotes by deleting your question? – Martin James Mar 08 '16 at 09:04
  • Initially I wrote ´i=0´ instead of ´i=1´ which gave me the output ´inf´. –  Mar 08 '16 at 09:04
  • Because my reputation is being degraded on stackoverflow also. –  Mar 08 '16 at 09:07
  • If you cannot copy/paste code from the environment where you tested it, it's best to not ask the question. Transcribing code by hand is notoriously error-prone and results in cockups like this one:) Your error upon entering code diffferent than that you tested just wasted everyone's time. Copy/paste it, or don't post. – Martin James Mar 08 '16 at 09:08
  • I copy pasted it sir. I did the same mistake in the IDE as here. Kindly understand that. –  Mar 08 '16 at 09:13
  • 1
    Possible duplicate of [What is a debugger and how can it help me diagnose problems](http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Raedwald Mar 08 '16 at 10:20
  • 2
    @Raedwald That wasn't the question and this isn't the typical "what's wrong with my code" question (those should be closed as off-topic, not as duplicates). The question is if the algorithm is correct. Now as it happened, the code had several severe bugs. But that doesn't make it a duplicate of some debugger question. – Lundin Mar 08 '16 at 10:42
  • @Lundin The division by zero in the first iteration would be very obvious in a debugger. The pister has evidently nit tried to debug their code. – Raedwald Mar 08 '16 at 12:39
  • Anyway since the OP insists on trying to "edit-fix" all of the code, I don't think this question is salvageable. – Lundin Mar 08 '16 at 12:44
  • 1
    Questions solvable by basic debugging are unwelcome: http://meta.stackoverflow.com/questions/254094/question-that-can-be-solved-using-basic-debugging – Raedwald Mar 08 '16 at 12:52
  • @Raedwald why are you typing like Officer Crabtree? – Martin James Mar 08 '16 at 14:44
  • 1
    @ProgyadeepMoulik Ask a new question, this one is asked and answered. – Robert Longson Mar 11 '16 at 14:51

3 Answers3

8

The algorithm was run in C and JAVA and both gave the output as inf.

That is because there is a bug in your code. You are starting with i == 0. When you calculate 1.0 / 0 you get an INF.

The series is supposed to start with i == 1 ...

You edited the question to fix to that particular bug.

Even so, you still will never get a correct value for the sum to infinity. The series diverges (goes to infinity) but given the way you are calculating it, there is no way that you will get there.

Eventually, you will reach a point where 1.0/i is too small to change sum and you will break out of the loop. I expect that will happen before i == Integer.MAX_VALUE ... but if it didn't, then you would run into ANOTHER bug in your code. If i ever reached Integer.MAX_VALUE then it would wrap around to Integer.MIN_VALUE and you will start adding negative terms to the sum. Oops!


Actually, what you are trying to calculate is the Harmonic Series. The partial sums (for N terms) converge to loge N + E, where E is the Euler–Mascheroni constant.

Source: https://en.wikipedia.org/wiki/Harmonic_series_%28mathematics%29#Partial_sums

From this, one should be able to estimate when the difference between Nth partial sum and 1.0 / N becomes large enough to stop the iteration.

A final note: you will get more accurate sums if you sum in the opposite direction; i.e. starting with very large N and summing with N reducing to 1.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Yeah that was a small mistake. –  Mar 08 '16 at 07:27
  • 1
    A "small mistake" which caused the result you are seeing. If you fix it, you won't see INF's – Stephen C Mar 08 '16 at 07:28
  • I changed the for statement to `for(int i=1;;i++)`. Umm...the ide used for **C** is a mobile app. And I'm having a problem. It'd be nice if someone tells me the output when the loop starts from **i=1**. –  Mar 08 '16 at 07:33
  • 1
    @ProgyadeepMoulik When there are posted answers, please don't edit the question into something entirely different that invalidates the posted answers. Instead, ask a new question. If needed, post a link to this one. I'll rollback your edit now, you'll still have your question changes available in the edit history. – Lundin Mar 08 '16 at 07:57
  • @Ludin I cannot delete the question. Why? –  Mar 08 '16 at 08:02
  • 1
    @ProgyadeepMoulik there are upvoted answers, eg. this one. – Martin James Mar 08 '16 at 08:53
  • @ProgyadeepMoulik - That is correct. People have spent time and effort answering your question. It is no longer up to you to decide if the Question + Answers worth keeping. This is now >>community<< property. – Stephen C Mar 08 '16 at 10:38
  • I think, ignoring the error, I should expect people to answer the real question. –  Mar 08 '16 at 12:05
  • If you read my answer properly, you will see that I do address the real question. – Stephen C Mar 08 '16 at 12:18
  • This error in his code would be very obvious if he had used a debugger. – Raedwald Mar 08 '16 at 12:54
  • @Raedwald debugger? I suspect that the OP did not even build/test it! – Martin James Mar 08 '16 at 14:49
  • @Stephen C Thanks for your explanation. Sorry I was so busy tackling the chaos that I didn't notice you'd already given an explanation. But one thing though. If it is so, as you explained in your answer about the other bug, how do you think did that other guy got the output? I was told that he got **5.17..** something like that. That was in **C**. –  Mar 08 '16 at 15:54
  • We need the source code for the C and Java versions to answer that. – Stephen C Mar 08 '16 at 16:04
2

There are many problems with your code. Your program doesn't work, it only seems to work.

  • Never compare float numbers for equality.
  • Computers can't divide by zero.
  • Literals 0.0 are of type double. Meaning that the calculation sum+(1.0/i) is performed on type double, which might be a larger type than float on the particular system. Your code assumes that float and double have the same representation, so it is non-portable.

    Therefore the result may not be too large during the calculation, which is done on type double, but it doesn't fit when you try to show it back into a float. Instead use f prefix on all literals, that is: 1.0f. Or just use double consistently all over the program.

  • Avoid cryptic loops. There's no need to move the loop condition inside the loop body. Your loop should look something like for(int i=0; float_compare(sum+1.0f/i, sum); i++), where float_compare is some way to compare float numbers. Something like this:

    #include <math.h>
    #define EPSILON 0.00001f
    
    inline bool float_compare (float x, float y)
    {
      return fabsf(result - expectedResult) < EPSILON;
    }
    
Community
  • 1
  • 1
Lundin
  • 195,001
  • 40
  • 254
  • 396
1

Some notes The range of i is important - integers have only fixed representations.

The series 1/1 + 1/2 + 1/3 + 1/4 ... is divergent (wikipedia : sum of recipricals)

The range of an int wraps, and so you would also be adding -1/1 -1/2 ... which would tend to 0.

The series progresses to infinity very slowly, so a computer may not be the best way of working it out.

mksteve
  • 12,614
  • 3
  • 28
  • 50