1 # 整数部分十进制转二进制
2
3 num = int(raw_input(">>>"))
4
5 if num < 0:
6 isNeg = True
7 num = abs(num)
8 else:
9 isNeg = False
10 result = ''
11 if num == 0:
12 result = ''
13 while num > 0:
14 result = str(num%2) + result
15 num = num/2
16 if isNeg:
17 result = '-' + result
18 # 小数部分十进制转二进制
19
20 x = float(raw_input('Enter a decimal number between 0 and 1: '))
21
22 p = 0
23 while ((2**p)*x)%1 != 0:
24 print('Remainder = ' + str((2**p)*x - int((2**p)*x)))
25 p += 1
26
27 num = int(x*(2**p))
28
29 result = ''
30 if num == 0:
31 result = ''
32 while num > 0:
33 result = str(num%2) + result
34 num = num/2
35
36 for i in range(p - len(result)):
37 result = '' + result
38
39 result = result[0:-p] + '.' + result[-p:]
40 print('The binary representation of the decimal ' + str(x) + ' is ' + str(result))
# 穷举法猜测检验平方根
x = 25
epsilon = 0.01
step = epsilon**2
numGuesses = 0
ans = 0.0
while (abs(ans**2 - x)) >= epsilon and ans <= x:
ans += step
numGuesses += 1
print('numGuesses = ' + str(numGuesses))
if abs(ans**2-x) >= epsilon:
print('Failed on square root of ' + str(x))
else:
print(str(ans) + ' is close to the square root of ' + str(x))
# 二分法猜测检验平方根
# bisection search for square root x = 12345
epsilon = 0.01
numGuesses = 0
low = 0.0
high = x
ans = (high + low)/2.0
while abs(ans**2 - x) >= epsilon:
print('low = ' + str(low) + ' high = ' + str(high) + ' ans = ' + str(ans))
numGuesses += 1
if ans**2 < x:
low = ans
else:
high = ans
ans = (high + low)/2.0
print('numGuesses = ' + str(numGuesses))
print(str(ans) + ' is close to square root of ' + str(x))
# Lecture 3.7, slide 3 # 牛顿-罗斐逊 算法搜寻平方根(g-(g**2-k)/2g) epsilon = 0.01
y = 24.0
guess = y/2.0 while abs(guess*guess - y) >= epsilon:
guess = guess - (((guess**2) - y)/(2*guess))
print(guess)
print('Square root of ' + str(y) + ' is about ' + str(guess)) #第一个python程序
import pickle as p linkmanfile = 'linkman.data'
#the name of the file where we will store the object linkman = { 'zhangyunpeng' : '',
'xuleisen' : '',
'yinrui' : '',
'yancangkuo' : '',
'lijizhou' : '',
'liuyulong' : ''
}
#set up linkman data base print '%d lineman:' % len(linkman)
for name, qq in linkman.items():
print '%s : %s' % (name, qq)
#list original listing print'(1-search 2-delete 3-add 0-revise)'
#prompting of operation k = int(raw_input('please input:'))
if k == 1:
s = raw_input('Search the linkman name:')
print '%s' % linkman[s] elif k == 2:
d = raw_input('delete the linkman name:')
del linkman[d] elif k == 3:
a = raw_input('add the linkman name:')
A = raw_input('add the linkman number:')
linkman[a] = A elif k == 0:
r = raw_input('which revise:')
linkman[r] = raw_input('revised number:')
#code of process for name, qq in linkman.items():
print '%s : %s' % (name, qq)
#print new listing f = file(linkmanfile, 'w')
p.dump(linkman, f)
#put data into a file for using next