Recently I encountered a programming question, where I had to find the volume of a n dimensional sphere, given its number of dimensions n and radius R.
I googled it, but did not find a good blog or paper detailing the whole process or method to calculate it. On Wikipedia, They have given a formula but did not mention how to calculate inner values clearly.
This is the general formula for calculating volume of a N dimensional sphere. The numerator part can be easily calculated as we already know the values of π, n and R. The denominator part is called gamma function. There are two basic rules (here in this calculation) for calculating Γ(n).
- If n is a positive integer, then Γ(n) = (n-1)!. You know what ! is right? Its factorial, which means (n-1)! = (n-1)(n-2)(n-3)...(1).
- If n/2 is a positive half integer, then -
So, based on (n/2 + 1) = (n+2)/2, we assume that n = (n+2) and put it in the formula. What I mean to say, is calculate Γ((n+2)/2).
This is called double factorial. There are two rules for calculating (n)!!.
- If n is even, (n)!! = (n)(n-2)(n-4)....(4)*(2).
- If n is odd, (n)!! = (n)(n-2)(n-4)....(3)*(1)
So, let me directly introduce you to the steps of calculating the volume of a n dimentional sphere -
- Calculate the numerator part using the values of n and R.
- To calculate the denominator, there are two different methods based on if the n is even or odd.
- If n is even, denominator = (n/2+1)!
- If n is odd, denominator = Γ((n+2)/2). You now already know how to calculate this, right?
from math import pi, sqrt, pow
# function for calculating double factorial
def double_fact(n):
n = n + 2
ans = 1
if n % 2:
for i in range(1, n - 1, 2):
ans *= i
else:
for i in range(2, n - 1, 2):
ans *= i
return ans
# taking input of number of dimensions and radius of sphere
n = int(input())
r = int(input())
# calculating numerator part
numo = (pow(pi, n / 2) * pow(r, n))
# calculating denominator part
if n % 2:
deno = double_factorial(n)
deno *= sqrt(pi / pow(2, n - 1))
else:
deno = 1
for i in range(1, (n // 2 + 1)):
deno *= i
# calculating final answer
ans = numo / deno
print("Volume: ", ans)