def factorial(x):
m=1
if x == 0:
return 1
for i in range(1,x+1):
m = m*i
return m
if __name__ == "__main__":
x=10
v=factorial(x)
print("%d 的阶乘是 %d"%(x,v))
极坐标方程为:
ρ = r ⋅ ( 1 − sin θ ) \rho=r\cdot(1-\sin \theta) ρ=r⋅(1−sinθ)
其中, θ ∈ [ 0 , 2 π ) \theta\in[0,2\pi) θ∈[0,2π)
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
def Descartes_heart(r):
x=np.linspace(0, 2*np.pi, 500)
rho = r*(1-np.sin(x))
plt.subplot(polar=True)
plt.plot(x, rho, c='r')
plt.text(0,0,'Heart', color='m')
plt.show()
if __name__ == "__main__":
a = 6
Descartes_heart(a)
S A = π ⋅ 1 2 2 ∗ 2 ≈ m n \frac{S}{A}=\frac{\pi\cdot 1^2}{2*2}\approx\frac{m}{n} AS=2∗2π⋅12≈nm
则
π → 4 m n , 当 n → ∞ \pi\to\frac{4m}{n}, \;\;\;\;\;\text{当}\;\;\;\; n\to\infty π→n4m,当n→∞
def PI_approx_for(n):
m=0
for i in range(1,n+1):
x=random()*2-1 #x的取值范围为[-1,1)
y=random()*2-1 #y的取值范围为[-1,1)
if x**2+y**2<1:
m = m+1
return 4*m/n
from random import random
if __name__ == "__main__":
n=100000
c1=PI_approx_for(n)
print('总实验次数是%d,计算的圆周率是%f'%(n,c1))
def PI_approx_np(n):
data = np.random.random((n,2))*2-1
plt.scatter(data[:,0],data[:,1],c='blue',marker='.')
temp = np.sum(data**2, axis=1)
label = temp<1
plt.scatter(data[label,0],data[label,1],c='red',marker='.')
plt.show()
c = 4*np.sum(label)/n
return c
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
if __name__ == "__main__":
n=10000
c2 = PI_approx_np(n)
print('总实验次数是%d,计算的圆周率是%f'%(n,c2))
判定公历闰年应遵循的一般规律为:四年一闰,百年不闰,四百年再闰.
def RunYear(y):
if y%4==0 and y%100!=0 : #能被4整除,但不是百年的是闰年
return 1
elif y%400==0 : #能被400年整除的是闰年
return 1
else:
return 0 #不是闰年
try:
year=int(input('输入年份:'))
if year>=0 :
r1=RunYear(year)
if r1 :
print('%d是闰年'%(year))
else:
print('%d不是闰年'%(year))
else:
print('输入年份值不对!')
except:
print('输入值有误!')