(2) 回顾mitx-6.00.1x-week2-3

回顾mitx-6.00.1x-week2

@Date    : 2018-07-18
@Author  : lmingzhi (lmingzhi@gmail.com)
@Link    : 
@Version : ver1.0

[TOC]

2018.07.18

week 2-3 Simple Algorithms

3.1 Video So far ...

注意点:

  • Strings are ‘immutable’, can not be modified.
s = 'hello'
s[0] = 'y'  # →  cause error
s = 'y' + s[1:] # assign 'yello' to s, s is a new object
for char in s:
    if char == 'i' or char == 'u':
        print('char is i or u')

3.2 Video Approximate solution

solution to find cube

  1. can use exhaustive enumueration (It is a good enough solution)
  2. start with a guess and incremently some small value
  3. e.g. |\text{guess}^3 - \text{cube}| <= \text{epsilon}

Observations - find square root

  1. step could be any small number
    • if too small, takes a long time to find square root
    • if too large, might skip over answer without getting close enough
  2. In general, will take x/step times through code to find solution
  3. 复杂度O(n) → need a more efficient way to do this

3.3 Video Bisection Search

二分查找:

  • 适用于已排好序的序列
  • 适用于查找某个区间的某个值
  • 有递归的思维在其中
  • 要求输入与输出单调变化才起作用(bisection search works when value of function varies monotonically with input), 如求解0-1之间的均立方根,可以乘以一个1000的倍数(系数)后,再进行。

step:

  1. if not close enough, guess too big or too small (search 0 ~ x)
  2. if g ** 2 > x, then know g is too big, so now search 0 ~ g
  3. and if , for example, this now g is such that g ** 2 < x, then know too small, so now search next g(搜索区间next g ~ g)
  4. 算法复杂度 O(logn)

search space:

  • first guess: N/2
  • second guess: N/4
  • gth guess: N/2^g

Observations:

  1. Bisection search radically reduce computation time - being smart about generating guess is important
  2. should work well on problems with 'ordering' property - value of function being solved varies monotonically with input value. (e.g. Here function is g**2, which grows as g grows.)

2018-07-19

Exercise: guess my number

# week2-3 Exercise: guess my number

print('Please think of a number between 0 and 100!')
low = 0
high = 100

def guess_wrong_ans(ans):
    global high, low, mid
    if ans == 'c':
        print('Game over. Your secret number was: %s' % mid)
        return False 
    elif ans == 'h':
        high = mid
    elif ans == 'l':
        low = mid
    else:
        print('Sorry, I did not understand your input.')
    return True

status = True
while status:
    mid = (low + high)//2   
    print('Is your secret number %s?' % mid)
    ans = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")
    status = guess_wrong_ans(ans)

3.4 Video: Floats and Fractions

Seeking how machines store float!

3.4.1 十进制转二进制(整数)

for Decimal numbers:

302 = 3 * 10^2 + 0 * 10^1 + 2 * 10^0

for Binary number:

10011 = 1 * 2^4 + 0 * 2^3 + 0 * 2^2 + 1 * 2^1 + 1 * 2^0
      = 16 + 0 + 0 + 2 + 1
      = 19

Internally, computer represents numbers(int or float) in binary!

十进制转二进制思路:

  1. x = 10011 (二进制,即十进制的19, 1 * 2^4 + 0 * 2^3 + 0 * 2^2 + 1 * 2^1 + 1 * 2^0)
  2. x % 2 → 1 (最后一位)
    • that gives us the last binary bit
  3. x // 2 → 右移一位,即 1 * 2^3 + 0 * 2^2 + 0 * 2^1 + 1 * 2^0
    • all the bits get shifted right
  4. 重复step2和step3, 再分别得到1,0,0,1(首位)
  5. 因此19的二进制表示为:10011

用二进制表示整数可以准确的储存

num = 19
if num < 0: 
    isNeg = True
    num = abs(num) 
else: 
    isNeg = False 
    result = ''
if num == 0: 
    result = '0' 
while num > 0: 
    result = str(num % 2) + result 
    num = num // 2 
if isNeg:
    result = '-' + result
print(result)

3.4.2 处理分数 how to deal with fractions

e.g. 简单的3/8

3/8 = 0.375
    = 3 * 10^(-1) + 7 * 10^(-2) + 5 * 10^(-3)
    = (3 * 10^1 + 7 * 10^1 + 5 * 10^0) / 10^3

So if we multiply by a power of 2 big enough to convert into a whole number,
can then convert to binary, and then divide by the same power of 2

即先乘以2的幂次方,转化为整数(整数可以直接转为二进制),然后再除以2的幂次方(相当于向左移动二进制的小数点)

  1. 0.375 * (23) = 3 (decimal)
    2.Convert 3 to binary (now 11)
    3.Divide by 2
    3 (shift right) to get 0.011 (binary)
x = 0.375
p = 0
while ((2**p)*x) % 1 != 0:
    print('Remainder = ' + str((2**p)*x - int((2**p)*x)))
    p += 1
num = int(x*(2**p))

result = ''
if num == 0:
    result = '0'
while num > 0:
    result = str(num%2) + result
    num = num//2

for i in range(p - len(result)):
    result = '0' + result

result = result[0:-p] + '.' + result[-p:]
print('The binary representation of the decimal ' + str(x) + ' is ' + str(result))
Remainder = 0.375
Remainder = 0.75
Remainder = 0.5
The binary representation of the decimal 0.375 is .011
# 二进制转十进制
binary = '0001100110011001100110011001100110011001100110011001101'
def binary2decima(binary):
    decimal = 0
    for digit in binary:
        decimal= decimal*2 + int(digit)
    return decimal

SOME IMPLICATIONS

  • If there is no integer p such that x(2*p) is a whole number, then internal representation is always an approximation
  • Suggest that testing equality of floats is not exact
    • Use abs(x-y) < some small number, rather than x == y
  • Why does print(0.1) return 0.1, if not exact?
    • Because Python designers set it up this way to automatically round

以上解释了为什么小数是不精确的,比如0.1是找不到一个2**k的数与之相乘(k要求为整数),从而获得一个整数

3.5 Video: Newton-Raphson

General approximation algorithm to find roots of a polynomial in one variable

p(x) = a_nx^n + a_{n-1}x^{n-1} + ... + a_1x^n + a_0

  • Want to find r such that p(r) = 0
  • Newton showed that if g is an approximation to the root, then g - p(g) / p’(g) is a better approximation; where p’ is derivative of p.

Simple case: cx^2 + k, 步骤:

  1. First derivative: 2cx
  2. Newton-Raphson says given a guess g for root; a better guess is g – (g^2 – k)/2g
  3. 循环迭代 g = g – (g^2 – k)/2g, 直至收敛
epsilon = 0.01
y = 24.0
guess = y/2.0
numGuesses = 0

while abs(guess*guess - y) >= epsilon:
    numGuesses += 1
    guess = guess - (((guess**2) - y)/(2*guess))

print('numGuesses = ' + str(numGuesses))
print('Square root of ' + str(y) + ' is about ' + str(guess))

迭代算法思维

Iterative algorithms

  • Guess and check methods build on reusing the same code
  • Use a looping construct to generate guesses, then check and continue

产生的guess算法有:

  • Exhaustive enumeration
  • Bisection search
  • Newton-Raphson (for root finding)

思考题:

  1. 为什么说计算机储存整数(int)是精确的,而储存小数(float)则是不精确的? 大家可以思考讨论一下。
  1. Guess and Check methods中,产生guess的有:
    • Exhaustive Enumeration 穷举法
    • Bisection search 二分法
    • Newton-Raphson 计算根(for root finding)

可以简述一下Guess and Check的流程关键要素吗?上述3种方法有什么特点?

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,980评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,422评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,130评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,553评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,408评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,326评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,720评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,373评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,678评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,722评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,486评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,335评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,738评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,009评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,283评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,692评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,893评论 2 335

推荐阅读更多精彩内容