【跟着MIT学Python】Unit 2.3 Simple Algorithms

REVIEW

Strings

s = 'abcdefg'
s[::-1] = ‘gfedcba’

strings are immutable type, can not be modified. [CANNOT assign a number to a piece of a string]

For loop

for char in s:
	if char == 'i' or char =='o':
		print('There is a i or o') 

APPROXIMATE SOLUTIONS

BISCTION SEARCH

Pick a value in the middle first.

x =25
epsilon = 0.01
numGuesses = 0
low = 0
high = x
ans = (low + high)/2

while (ans**2 - x) >= epsilon

Floats and Fractions

  • Decimal number:

302 = 3102+0*101+210^0

  • Binary number:

10011 = 124+0*23+022+1*21+1*2^0

Convert decimal integer to binary

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'

Fractions

3/8 = 0.375 = 3E-3+7E-2+5E-3

  • Convert de fraction into the decimal

0.375*(2**3) = 3 (which is decimal)

  • Convert decimal to binary

3→11

  • Divide by 2**3(shift left) to get 0.011(binary)

NEWTON-PRPHSON

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

p ( x ) = a n x n + a n − 1 x n − 1 + . . . + a 1 x + a 0 p(x)=a_nx^n+a_{n-1}x^{n-1}+...+a_1x+a_0 p(x)=anxn+an1xn1+...+a1x+a0

  • Want to find r such that p® = 0
  • Newton showed that if g is an approx. to the root, then

g − p ( g ) / p ′ ( g ) g-p(g)/p'(g) gp(g)/p(g)

is a better approx.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值