Python Course homework 1

这是 Python 课程的第一次作业

其他两次作业可以点击这里: Python Course Homework 2 Python Course Homework 4

Python

Exercise 1

Recall that n!n! is read as “n^n factorial” and defined as n!=n\times(n-1)\times\cdots\times2\times1n!=n\times(n-1)\times\cdots\times2\times1

There are functions to compute this in various modules, but let’s write our own version as an exercise.

In particular, write a function factorial such that factorial(n) returns n!n! for any positive integer n.

# -*- coding: utf-8 -*-
"""
Created on Tue Oct 16 23:01:45 2018

@author: Wengsway

"""

def factorial(n):
      if n < 2:
            return 1
      else:
            return n*factorial(n-1)
n = int(input('please input any positive integer:'))
print(factorial(n))

Exercise 2

The binomial random variable Y∼Bin(n,p)Y∼Bin(n,p) represents the number of successes in nn binary trials, where each trial succeeds with probability pp

Without any import besides from numpy.random import uniform, write a function binomial_rv such that binomial_rv(n, p) generates one draw of YY

Hint: If UU is uniform on (0,1)(0,1) and p∈(0,1)p∈(0,1), then the expression U < p evaluates to True with probability p

# -*- coding: utf-8 -*-
"""
Created on Wed Oct 17 18:26:42 2018

@author: Wengsway

"""

import numpy as np

def factorial(n):
      if n < 2:
            return 1
      else:
            return n*factorial(n-1)
u = np.random.normal(0,1)
N = int(input("Please input the N value:"))
def binomial_rv(n,p):
      y = p**n * (1-p)**(N-n) * factorial(N)/(factorial(n) * factorial(N-n))
      return y
n = int(input("Please input the n value:"))
p = float(input("Please input the p value:"))
print(binomial_rv(n,p))

Exercise 3

Compute an approximation to ππ using Monte Carlo. Use no imports besides

import numpy as np

Your hints are as follows:

  • If is a bivariate uniform random variable on the unit square , then the probability that lies in a subset of is equal to the area of
  • If U1,…,Un are iid copies of , then, as gets large, the fraction that fall in converges to the probability of landing in
  • For a circle, area = pi * radius^2
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 17 10:23:25 2018

@author: Wengsway

"""

import numpy as np

frequency = 0
numbers = int(input("Please input the number of times:"))
for i in range(1, numbers):
    x, y = np.random.uniform(0,1), np.random.uniform(0,1)
    area = np.sqrt(x**2 + y**2)
    if area <= 1.0:
        frequency = frequency + 1
pi = 4 * (frequency/numbers)
print(pi)
相关文章
Python Course homework 2

这是 Python 课程的第二次作业 其 阅读更多

3 个 Python 编程小练习

3 个 Python 小练习:(1)查询 阅读更多

这篇文章有 3 个评论

发表评论