7
$\begingroup$

I used the code in the second answer on this page to switch from Cartesian to Spherical coordinates and integrate a function over the sphere. I would like to use this code to calculate the volume of a sphere. However if I set $ f(x, y, z) = 1 $, I get the following output:

$ -\frac{1}{3}r^3 \varphi\cos(\theta) $

Here is the code I used:

Needs["VectorAnalysis`"]

JacobianDeterminant[Spherical[r, θ, ϕ]]

f[x_, y_, z_] := 1

Integrate[
 f @@ CoordinatesToCartesian[#, Spherical @@ #] JacobianDeterminant[
     Spherical @@ #] &@{r, θ, ϕ},
 r, θ, ϕ]

How can I make the code return the volume of a sphere which is $\frac{4}{3}\pi r^3$?

$\endgroup$
10
$\begingroup$

Employing most of your own code;

Integrate[
 f @@ CoordinatesToCartesian[#, Spherical @@ #] JacobianDeterminant[Spherical @@ #] &@{r, θ, ϕ}, 
 {r, 0, R}, {θ, 0, π}, {ϕ, -π, π}
 ]

(4 π R^3)/3

That is, you just have to add the integral boundaries.

$\endgroup$
5
$\begingroup$

Try this

transform[f : (_Function | _Symbol), coordi_: {x, y, z}, coordf_: {r, θ, ϕ}] := Module[{rules, jdet},
          rules = Thread[coordi -> CoordinateTransformData["Spherical" -> "Cartesian", "Mapping", coordf]];
          jdet = CoordinateTransformData["Spherical" -> "Cartesian", "MappingJacobianDeterminant", coordf];
          jdet f @@ coordi /. rules
         ]

f[x_, y_, z_] := 1

Integrate[transform[f], r, {θ, 0, π}, {ϕ, 0, 2 π}]
(4 π r^3)/3
$\endgroup$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.