N-dimensional Circles!
Mathematica, 18 bytes, up to ~168.15 trillion dimensions
Pi^(a=.5#)/a!#2^#&
Anonymous function. Takes two numbers as input, and returns an inexact number as output. Works with any number of dimensions. Outputs 1.
for n = 0. Uses the formula from Volume of an n-ball on Wikipedia.
Explanation
We are attempting to compute πn/2/Γ(n/2 + 1)·Rn, or N[Pi^(n/2)/Gamma[n/2 + 1] R^n]
in Mathematica. In our case, #
(first argument) is n and #2
(second argument) is R. This leaves us with N[Pi^(#/2)/Gamma[#/2 + 1] #2^#] &
, which can be golfed as follows:
N[Pi^(#/2)/Gamma[#/2 + 1] #2^#] &
Pi^(.5#)/Gamma[.5# + 1] #2^# & (* replace exact with approximate numbers*)
Pi^(.5#)/(.5#)! #2^# & (* n! == Gamma[n + 1] *)
Pi^(a=.5#)/a! #2^# & (* replace repeated .5# *)
Pi^(a=.5#)/a!#2^#& (* remove whitespace *)
and thus, our original program.
Jelly, 13 bytes + extra swag
÷2µØP*÷!
ç×*@
Try it online!
Works for any dimension, so long as the fixed value of π yielded by ØP
(3.141592653589793
) is accurate enough.
How?
÷2µØP*÷! - Link 1: n, r
÷2 - n / 2
µ - monadic chain separation
ØP - π (3.141592653589793)
* - exponentiate: π^(n/2)
! - Pi(n/2): Gamma(n/2 + 1)
÷ - divide: π^(n/2) / Gamma(n/2 + 1)
ç×*@ - Main link: n, r
ç - call last link (1) as a dyad: π^(n/2) / Gamma(n/2 + 1)
*@ - exponentiate with reversed @rguments: r^n
× - multiply: r^n * π^(n/2) / Gamma(n/2 + 1)
R, 75 40 38 bytes (plus extra swag)
Well, looks like I could golf this down by giving in and using the gamma function rather than recursive functions.
function(n,r)pi^(n/2)/gamma(n/2+1)*r^n
Defines an anonymous function to calculate the volume of an n
-dimensional hypersphere of radius r
.
Some examples:
1 1 -> 2
0 48 -> 1
2 3 -> 28.27433
3 4.5 -> 381.7035
7 7 -> 3891048
100 3 -> 122051813
Swagless solution, 38 34 bytes
For a few bytes less, you can have an anonymous function that only works for dimensions 1 to 3. Returns numeric(0)
for n=0
, and NA
for n>3
. (numeric(0)
is a numeric vector of length 0; NA
is for "not available".) Performance is otherwise identical to the general solution above.
function(n,r)c(1,pi,4/3*pi)[n]*r^n