标签:
1 1 # 整数部分十进制转二进制 2 2 3 3 num = int(raw_input(">>>")) 4 4 5 5 if num < 0: 6 6 isNeg = True 7 7 num = abs(num) 8 8 else: 9 9 isNeg = False 10 10 result = ‘‘ 11 11 if num == 0: 12 12 result = ‘0‘ 13 13 while num > 0: 14 14 result = str(num%2) + result 15 15 num = num/2 16 16 if isNeg: 17 17 result = ‘-‘ + result 18 18 # 小数部分十进制转二进制 19 19 20 20 x = float(raw_input(‘Enter a decimal number between 0 and 1: ‘)) 21 21 22 22 p = 0 23 23 while ((2**p)*x)%1 != 0: 24 24 print(‘Remainder = ‘ + str((2**p)*x - int((2**p)*x))) 25 25 p += 1 26 26 27 27 num = int(x*(2**p)) 28 28 29 29 result = ‘‘ 30 30 if num == 0: 31 31 result = ‘0‘ 32 32 while num > 0: 33 33 result = str(num%2) + result 34 34 num = num/2 35 35 36 36 for i in range(p - len(result)): 37 37 result = ‘0‘ + result 38 38 39 39 result = result[0:-p] + ‘.‘ + result[-p:] 40 40 print(‘The binary representation of the decimal ‘ + str(x) + ‘ is ‘ + str(result)) 41 # 穷举法猜测检验平方根 42 x = 25 43 epsilon = 0.01 44 step = epsilon**2 45 numGuesses = 0 46 ans = 0.0 47 while (abs(ans**2 - x)) >= epsilon and ans <= x: 48 ans += step 49 numGuesses += 1 50 print(‘numGuesses = ‘ + str(numGuesses)) 51 if abs(ans**2-x) >= epsilon: 52 print(‘Failed on square root of ‘ + str(x)) 53 else: 54 print(str(ans) + ‘ is close to the square root of ‘ + str(x)) 55 # 二分法猜测检验平方根 56 # bisection search for square root 57 58 x = 12345 59 epsilon = 0.01 60 numGuesses = 0 61 low = 0.0 62 high = x 63 ans = (high + low)/2.0 64 while abs(ans**2 - x) >= epsilon: 65 print(‘low = ‘ + str(low) + ‘ high = ‘ + str(high) + ‘ ans = ‘ + str(ans)) 66 numGuesses += 1 67 if ans**2 < x: 68 low = ans 69 else: 70 high = ans 71 ans = (high + low)/2.0 72 print(‘numGuesses = ‘ + str(numGuesses)) 73 print(str(ans) + ‘ is close to square root of ‘ + str(x))
标签:
原文地址:http://www.cnblogs.com/Lindaman/p/4393725.html