python学习实例(1)

#======================================
#1.2 计算机编程的基本概念
#======================================

#++++++++++++++++++++++++++++++++++++++
#1.2.2 从Python语言进入计算机语言的世界
#++++++++++++++++++++++++++++++++++++++

#<程序:例子1>
def  F(x,y):
    return(x*x+y*y)
print("F(2,2)=",F(2,2))
print("F(3,2)=",F(3,2))



#<程序:例子2>
def  Pr():
        for i in range(0,10): # 索引 i = 0 to 9
                print("Hello world")
#在函数程序外面Pr()
Pr()
# 输出 Hello world 10 遍



#<程序:布尔类型例子>
b = 100<101
print(b)



#<程序:for循环例子>
for i in range(1, 5): 
	print(i)  



#<程序:while循环例子>
i = 1
while i<5:
    print(i)
    i=i+1



#<程序:if语句例子>
i=10
j=11
if i< j:
	print("i<j")
else:
	print("i>=j")


#======================================
#1.3 计算机核心知识——算法(Algorithm)
#======================================

#++++++++++++++++++++++++++++++++++++++
#1.3.2 解平方根算法一
#++++++++++++++++++++++++++++++++++++++

#<程序:平方根运算1>
def square_root_1():  #函数定义,函数名为square_root_1
    c = 10				#所求平方根的输入,即该段程序求根号10
    i = 0				#记录执行循环次数
    g = 0
    for j in range(0,c+1):		#for 循环开始
        if (j * j > c and  g==0):#if 语句块,获取g,使得g2<c,(g+1)2>c
            g = j - 1
	#for 循环结束
    while (abs(g * g - c) > 0.0001):#判断g2-c是否在精度范围内,while循环
        g += 0.00001		#g每次加步长,以逼近所求解
        i = i+1
        print ("%d:g = %.5f" % (i,g))

#函数外,执行下面的语句
square_root_1()


#++++++++++++++++++++++++++++++++++++++
#1.3.3 解平方根算法二
#++++++++++++++++++++++++++++++++++++++

#<程序:平方根运算2-二分法>
def square_root_2():
    i = 0
    c = 10
    m_max = c
    m_min = 0
    g = (m_min+m_max)/2
    while (abs(g*g -c) > 0.00000000001):  #while循环开始
        if (g*g <c):
                m_min = g
        else:
                m_max = g
        g = (m_min + m_max)/2
        i = i+1
        print ("%d:%.13f" % (i,g))         #while循环结束
#函数之外执行
square_root_2 ()


#++++++++++++++++++++++++++++++++++++++
#1.3.4 解平方根算法三
#++++++++++++++++++++++++++++++++++++++

#<程序:平方根运算3-牛顿法>
def square_root_3():
    c = 10
    g = c/2
    i = 0
    while abs(g*g - c) > 0.00000000001:
        g = (g + c/g)/2
        i = i+1
        print("%d:%.13f" % (i,g))

square_root_3()



#======================================
#1.5 计算机前沿知识——大数据(Big Data)
#======================================

#++++++++++++++++++++++++++++++++++++++
#1.5.5 对数据和逻辑的正确态度
#++++++++++++++++++++++++++++++++++++++

#<程序:求圆周率-蒙地卡罗法>
import random
def pi(times):
    sum=0
    for i in range(times):
        x=random.random()
        y=random.random()
        d2=x*x+y*y		#算到原点的距离
        if d2<=1: sum+=1		#距离<=1, 代表在圆里面。
    return(sum/times*4)

#函数外执行
times=100000000
x=pi(times)
print("pi=%.8f"%(x))

 

©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页