##def sqrt(x) : ## guess = 1.0 ## while guess * guess != x: ## guess = (guess + x/guess)/2 ## return guess ##def sqrt(x) : ## guess = 1.0 ## n = 0 ## while abs(guess * guess - x) > 0.000000001 : ## guess = (guess + x/guess)/2 ## n = n + 1 ## print(str(n) + "th iteration:", guess) ## return guess # math包专门用于浮点数 ##from math import fabs ##def sqrt(x) : ## guess = 1.0 ## while fabs(guess * guess - x) >= 0.0001 : ## guess = (guess + x/guess)/2 ## return guess ### 两段说明浮点数计算误差的程序 ##### 加 0.1 重复 10 次,能等于 1.0 吗? ##x = 0.0 ##for n in range(10): ## x = x + 0.1 ##print("x == 1.0 is", x == 1.0) ##print("x is", x) ###### 希望循环体执行 100 次。实际做多少次? ##s = 0.0 ##n = 0 ##while s < 10.0 : ## s = s + 0.1 ## n = n + 1 ##print("Iterating", n , "times.","s =", s) ##ln2 = 0.0 ##for n in range(1, 21): ## ln2 += (-1)**(n-1) * 1/n ## ## ##ln2 = 0.0 ##n = 1 ##while n <= 20: ## ln2 += (-1)**(n-1) * 1/n ## n += 1 ##### 计算 sin(x) 的近似值 ###### 1 ####### ##def term(x, n): ## t = (-1)**n * x ** (2 * n + 1) ## for i in range(2, 2 * n + 2): ## t /= i ## return t ## ##def mysin(x): ## sn = 0.0 ## n = 0 ## while True: ## t = term(x, n) ## if abs(t) < 1e-6: ## return sn ## sn += t ## n += 1 ###### 2 ######## ##def mysin(x): ## sn = x ## t = x ## n = 0 ## while True: ## n += 1 ## t *= - x * x / (2*n) / (2*n + 1) ## if abs(t) < 1e-6: ## return sn ## sn += t ##### 简单的确定次数的输入循环 ########### ##print("Calculating average of 10 numbers") ##ss = 0.0 ##for i in range(10): ## x = float(input("Next number: ")) ## ss += x ##print("The average of these 10 numbers is", ss/10) ##### 输入控制的循环 ########### ##print("Calculating average.") ##ss = 0.0 ##n = 0 ##while True: ## snum = input("Next number ('None' to stop): ") ## if snum == "None": ## break ## ss += float(snum) ## n += 1 ##print("The average of these " + str(n) + " numbers is", ss/n) ##name = "" ##while name != "no more": ## name = input("Hi, friend! What is your name? ") ## print("Hello, " + name + "!\n") ##name = "" ##while True : ## name = input("Hi, friend! What is your name? ") ## if name == "no more": ## break ## print("Hello, " + name + "!\n") ##name = "" ##while True : ## name = input("Hi, friend! What is your name? ") ## if name == "no more": ## break ## s = "Hello, " + name + "!\n" ## print(s) ######### 程序终止性的例子 ########## ##def collatz(n): ## num = n ## count = 0 ## while n != 1: ## if n % 2 == 0: # n is even ## n = n//2 ## else: # n is odd ## n = n * 3 + 1 ## count += 1 ## print("For integer " + str(num) + " iterating " + ## str(count) + " times.") ## ##for i in range(20, 30): ## collatz(i) ###### 用 assert 检查输入的程序 ##from math import fabs ##def sqrt(x) : ## assert(x >= 0) ## guess = 1.0 ## while fabs(guess * guess - x) >= 0.0001 : ## guess = (guess + x/guess)/2 ## return guess ### Here we take n! == 1 for all n <= 0 ##def fact(n) : ## assert(type(n) == int and n >= 0) ## prod = 1 ## while n > 1: ## prod *= n ## n -= 1 ## return prod ## ##for n in range(1, 25, 3): ## print("Factorial of", n, "is", fact(n))