Skip to content

Instantly share code, notes, and snippets.

@edusanketdk
Created February 21, 2021 07:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edusanketdk/f376612decdfcfe511d1ebfb731a143a to your computer and use it in GitHub Desktop.
Save edusanketdk/f376612decdfcfe511d1ebfb731a143a to your computer and use it in GitHub Desktop.
Volume of n dimensional sphere

Volume of N dimensional sphere

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.

So, lets jump into the details:

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 -

But we have to calculate Γ(n/2 + 1), not Γ(n/2).

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).

Hey, what is (n-2)!! here?

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)

summarising the calculations:

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?

python code for developers:

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment