Python Course homework 1

2018年10月31日,老文章

Exercise 1

Recall that n!n! is read as “nn factorial” and defined as n!=n×(n?1)×?×2×1n!=n×(n?1)×?×2×1

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 U is a bivariate uniform random variable on the unit square (0,1)^2, then the probability that U lies in a subset B of (0,1)^2 is equal to the area of B
  • If U1,…,Un are iid copies of U, then, as n gets large, the fraction that fall in B converges to the probability of landing in B
  • 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)

Exercise 4

Write a program that prints one realization of the following random device:

  • Flip an unbiased coin 10 times
  • If 3 consecutive heads occur one or more times within this sequence, pay one dollar
  • If not, pay nothing

Use no import besides from numpy.random import uniform

# -*- coding: utf-8 -*-
"""
Created on Wed Oct 17 12:25:01 2018

@author: Wengsway

"""

from numpy.random import randint

x = randint(0,2,10).tolist()
j = 0
for i in range(len(x)-2):
      if x[i] == 1 and x[i+1] == 1 and x[i+2] == 1:
            j = j + 1
if j >= 1:
      print("You pay one dollar!")
else:
      print("You pay nothing!")

Exercise 5

Your next task is to simulate and plot the correlated time series
x_{t+1} = \alpha \, x_t + \epsilon_{t+1} \quad \text{where} \quad x_0 = 0 \quad \text{and} \quad t = 0,\ldots,T
The sequence of shocks {?_t} is assumed to be iid and standard normal

In your solution, restrict your import statements to

import numpy as np
import matplotlib.pyplot as plt

Set T=200 and α=0.9

# -*- coding: utf-8 -*-
"""
Created on Wed Oct 17 10:50:23 2018

@author: Wengsway

"""

import numpy as np
import matplotlib.pyplot as plt

def timeseries(α,T):
      x = [0]
      ε = np.random.randn(T)
      for t in range(T):
            x.append(α*x[t-1]+ε[t])
      return x
T = int(input('Please input the T:'))
α = float(input('Please input the α:'))
plt.figure(figsize=(10,5))
plt.plot(timeseries(α,T+1),color = 'Hotpink',label = 'x')
plt.legend()

Exercise 6

To do the next exercise, you will need to know how to produce a plot legend

The following example should be sufficient to convey the idea

import numpy as np
import matplotlib.pyplot as plt

x = [np.random.randn() for i in range(100)]
plt.plot(x, label="white noise")
plt.legend()
plt.show()

Now, starting with your solution to exercise 5, plot three simulated time series, one for each of the cases α=0, α=0.8 and α=0.98

In particular, you should produce (modulo randomness) a figure that looks as follows

not found

(The figure nicely illustrates how time series with the same one-step-ahead conditional volatilities, as these three processes have, can have very different unconditional volatilities.)

Use a for loop to step through the αα values

Important hints:

  • If you call the plot() function multiple times before calling show(), all of the lines you produce will end up on the same figure
    • And if you omit the argument 'b-' to the plot function, Matplotlib will automatically select different colors for each line
  • The expression 'foo' + str(42) evaluates to 'foo42'
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 17 12:14:49 2018

@author: Wengsway

"""

import numpy as np
import matplotlib.pyplot as plt

def timeseries(α,T):
      x = [0]
      ε = np.random.randn(T)
      for t in range(T):
            x.append(α*x[t-1]+ε[t])
      return x
T = int(input('Please input the T:'))
for i in range(3):
      α = float(input('Please input the α:'))    
      plt.figure(figsize=(10,5))
      plt.plot(timeseries(α,T+1),color = 'r',label = 'x')
      plt.legend()
      plt.show()

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,718評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件面睛,死亡現(xiàn)場離奇詭異,居然都是意外死亡尊搬,警方通過查閱死者的電腦和手機(jī)叁鉴,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,683評論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來佛寿,“玉大人幌墓,你說我怎么就攤上這事〖叫海” “怎么了常侣?”我有些...
    開封第一講書人閱讀 158,207評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長弹渔。 經(jīng)常有香客問我胳施,道長,這世上最難降的妖魔是什么捞附? 我笑而不...
    開封第一講書人閱讀 56,755評論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮您没,結(jié)果婚禮上鸟召,老公的妹妹穿的比我還像新娘。我一直安慰自己氨鹏,他們只是感情好欧募,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,862評論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著仆抵,像睡著了一般跟继。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上镣丑,一...
    開封第一講書人閱讀 50,050評論 1 291
  • 那天舔糖,我揣著相機(jī)與錄音,去河邊找鬼莺匠。 笑死金吗,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播摇庙,決...
    沈念sama閱讀 39,136評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼旱物,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了卫袒?” 一聲冷哼從身側(cè)響起宵呛,我...
    開封第一講書人閱讀 37,882評論 0 268
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎夕凝,沒想到半個(gè)月后宝穗,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,330評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡迹冤,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,651評論 2 327
  • 正文 我和宋清朗相戀三年讽营,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片泡徙。...
    茶點(diǎn)故事閱讀 38,789評論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡橱鹏,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出堪藐,到底是詐尸還是另有隱情莉兰,我是刑警寧澤,帶...
    沈念sama閱讀 34,477評論 4 333
  • 正文 年R本政府宣布礁竞,位于F島的核電站糖荒,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏模捂。R本人自食惡果不足惜捶朵,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,135評論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望狂男。 院中可真熱鬧综看,春花似錦、人聲如沸岖食。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,864評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽泡垃。三九已至析珊,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間蔑穴,已是汗流浹背忠寻。 一陣腳步聲響...
    開封第一講書人閱讀 32,099評論 1 267
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留存和,地道東北人锡溯。 一個(gè)月前我還...
    沈念sama閱讀 46,598評論 2 362
  • 正文 我出身青樓赶舆,卻偏偏與公主長得像,于是被迫代替她去往敵國和親祭饭。 傳聞我的和親對象是個(gè)殘疾皇子芜茵,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,697評論 2 351

推薦閱讀更多精彩內(nèi)容

  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,448評論 0 13
  • Words & Phrases - formative A formative period of time or...
    Alice愛學(xué)習(xí)閱讀 3,957評論 0 5
  • 17年阿里吹響了新零售的號角,實(shí)體零售紛紛借助互聯(lián)網(wǎng)工具提升客流倡蝙、消費(fèi) 目前采取較多的是微信服務(wù)號+訂閱號九串,阿里口...
    生活愛運(yùn)營閱讀 211評論 0 0
  • 和樊姐是在地鐵上認(rèn)識的。前一天晚上寺鸥,參加完小芮的婚禮后猪钮,從淄博到南京,坐了12個(gè)小時(shí)的汽車胆建,早上六點(diǎn)到南京汽車總站...
    敬哥閱讀 315評論 0 1
  • 期中考試中一篇散文閱讀《母親的額頭》笆载,感覺還是接地氣的呀扑馁,可學(xué)生呢。有的白卷凉驻,有的潦草應(yīng)付腻要,這篇文章真的就...
    言玔閱讀 104評論 0 1