Reputation: 203
I can easily calculate the volume of a sphere in python using this code.
import math
radius = input("Enter Radius: ")
print("Radius: " + str(radius))
r = float(radius)
volume = 4.0/3.0 * math.pi * (r*r*r)
print("Volume: " + str(round(volume,2)))
Now my plan is to find the volume in n dimension. The equation I have derived to find the volume and graphical changes of volume is that
I wanted to use like this
import math
dimension = input("Enter dimension: ")
print("dimension: " + str(dimension))
n = float(dimension)
volume = math.pi^(n/2)/math.gamma(n/2 + 1)
print("Volume: " + str(round(volume,2)))
It's not working. Can you help me finding the volume for different dimension with getting the plot for the volume of the sphere?
Upvotes: 0
Views: 11561
Reputation: 244311
You must change:
volume = math.pi(n/2)^2/math.gamma(n/2 + 1)
to:
volume = math.pi**(n/2)/math.gamma(n/2 + 1)
Complete code:
import math
dimension = input("Enter dimension: ")
print("dimension: " + str(dimension))
n = float(dimension)
volume = math.pi**(n/2)/math.gamma(n/2 + 1)
print("Volume: " + str(round(volume,4)))
Input:
Enter dimension: 3
Output:
dimension: 3
Volume: 4.1888
Additional:
import math
import matplotlib.pyplot as plt
x = []
y = []
for dimension in range(100):
n = float(dimension)
volume = math.pi**(n/2)/math.gamma(n/2 + 1)
x.append(n)
y.append(volume)
plt.plot(x, y)
plt.show()
Upvotes: 3
Reputation: 8966
Looks like pow()
is what you need:
import math
dimension = input("Enter dimension: ")
print("dimension: " + str(dimension))
n = float(dimension)
volume = pow(math.pi,(n/2))/math.gamma(n/2 + 1)
print("Volume: " + str(round(volume,2)))
pow(x,y)
Returns x to the power y.
Upvotes: 0