# Diff between (a+b)/2 and a+(b-a)/2

Hello People,

Do you know what is the difference between (a+b)/2 and a+(b-a)/2?

if not, then don’t worry. Here I’m with a good explanation. Mathematically it seems to be the same.

But in programming, you might get weird results. Let’s take an example.

int a = 1000000000;

int b = 2000000000;

print((a+b)/2);

print(a+(b-a)/2);Output:

-647483648

1500000000

As we can see that (a+b)/2 is giving me -647483648 and a+(b-a)/2 is giving me 1500000000 i.e correct.

**Why is this happening?**Since integers can store a maximum value of 2³¹ -1 (2147483647) in java. After that, it will go to the negative side. If you will do a+b first it will cross the integer limit and it will give you a negative result. But if you will do b-a(will be smaller) first and divide it by 2 ( will get much smaller ) and then add a.

int a = 2000000000;

int b = 1000000000;

print(a+b);

print((a+b)/2);

print(b-a);

print((b-a)/2);

print(a+(b-a)/2);Output:

-1294967296

-647483648

-1000000000

-500000000

1500000000

**Conclusion:**We should always use

**a+(b-a)/2**instead of

**(a+b)/2.**

If you like this article and found it interesting and knowledgeable, do hit the 👏 button and share it with your colleagues and friends.