0

I have been trying to calculate simple sum in Java (or a part of it at the beginning as you can see:) ).

https://wikimedia.org/api/rest_v1/media/math/render/svg/6eef71e528bb8ff23f29a82bf2dd240b39edf22f (sorry for not posting it as an image, I lack reputation...)

I have been testing it for few values of N, and then got strange results. I present you my code and the results.

class Sum {

public void sol(int N) {

    float sum=0.0f;

    for(int i=0;i<20;i++)
    {
        float first = (float) (N^2)/(4*i+1);
        float second = (float) (N^2)/(4*i+3);
        sum= sum+(first - second);
    }
    System.out.println(sum);

}
public static void main(String args[]){
    Sum sum=new Sum();
    sum.sol(0);
    sum.sol(1);
    sum.sol(2);
    sum.sol(3);
    sum.sol(4);

}

}

The results are: 1.5582982

2.3374474

0.0 (???)

0.7791491

4.674895

I had that calculated on my calculator and the results are completely different from those presented above. Could you give me a hand with understanding this and how to overcome that problem to achieve reliable numbers?

  • 1
    "sorry for not posting it as an image, I lack reputation...)" We don't want links or images here - just complete questions which stand alone and can be answered without relying on external resources which can disappear at any moment. –  Apr 05 '17 at 21:45
  • 1
    Write `N*N` instead of `N^2` (which is a binary XOR). – Socowi Apr 05 '17 at 21:47
  • @DrEval The image is fine, but it would have been better embedded. Best would be the image **and** what is trying to be computed in text (something like "Sum from 0 to infinity of (`floor(r^2/(4i + 1)) - floor(r^2/(4i+3)))`"). – Justin Apr 05 '17 at 21:47
  • @DrEval: Without TeX support on this site, images are the best option we have for mathematical notation. – user2357112 Apr 05 '17 at 21:53
  • Thank you for all the answers, I have made a mistake with the power... @DrEval - we can put images here, but as my reputation is very low I can't do that. I don't think image from wikipedia will soon disappear. I could use LaTeX or anything else, but first let me do that... –  Apr 06 '17 at 07:40

0 Answers0