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:
second methodCode:double getmass(double r){ double mass = 0; double radius; int max = 10000000; double step = r/max; if(r == 0) return 0; for(int i = 0; i <= max; i++){ radius = 0.0000001+i*step; mass += 4.*pi*1.*pow(radius,2)*step; // rho is set to 1. } 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.Code:double getmass2(double r){ double mass = 0; double radius, volume_new, volume_old; int max = 100000000; double step = r/max; if(r == 0) return 0; volume_old = 0.; for(int i = 1; i <= max; i++){ radius = i*step; 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; }
(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



LinkBack URL
About LinkBacks


