# Thread: typo in mass calculation

1. ## typo in mass calculation

Hay
I have a very easy question but I can't find my typo...
I want to calculate the mass of a globe. I have two methods and I need both and they should give the same result of course...
first method:

M(r) = int^r_0 4*pi*rho(r) dr

rho(r) is the density profile of the globe, we can set it to 1 for a constant profile (for simplicity).
second method:
I divide the globe into shells multiply each shell with rho and sum over it

the numerical implementations would be:
first method:

Code:
```double getmass(double r){
double mass = 0;
int max = 10000000;
double step = r/max;

if(r == 0) return 0;

for(int i = 0; i <= max; i++){
mass += 4.*pi*1.*pow(radius,2)*step; // rho is set to 1.

}

return mass;
}```
second method

Code:
```double getmass2(double r){
double mass = 0;
int max = 100000000;
double step = r/max;

if(r == 0) return 0;

volume_old = 0.;
for(int i = 1; i <= max; i++){
volume_new = (4/3)*pi*pow(radius,3);    // calculate the new volume
mass += (volume_new-volume_old)*1.;   // density profile is set to 1
volume_old = volume_new;                      // this will be the old volume in the next round
}

return mass;
}```
the problem is that both methods give not the same result. The equations are identical, I am sure that it is not a numerical result so it is probably a wrong implementation.
(A small program is attached which runs the methods explained above)
I am thankful for any help
best regards
florian

I found the problem... it is 4./3. not 4/3.. so stupid

2. The two code segments (as you've posted them) are not equivalent.

1) The values of max are different (count the zeros), so the step sizes are different.

2) The first value has a fudge factor when computing radius. That will affect results.

3) In the second function, the computation of volume_new has a factor (4/3). That is done in integer arithmetic, so is always equal to 1.

And the above are without even looking to see if the algorithms should be equivalent.

Unrelated to your problem, but if you want to compute the square of x, do "x*x" rather than pow(x,2). Any elementary numerical text will explain the benefits/tradeoffs. Similarly, the cube of x can be computed as x*x*x.