当前位置: 首页 > article >正文

鸢尾花书实践和知识记录[数学要素3-1万物皆数]

章节框图

文章目录

    • 本章用到的函数
    • 使用math库来打印出一些常用的值
    • 判断奇数偶数
    • 两数加减
    • 产生序列
    • 矩阵向量的表示:
    • 取数组矩阵元素的方法
    • streamlit的绘图
    • 矩阵的一般类型
    • 构造二维矩阵
    • 矩阵的加和运算

本章用到的函数

在这里插入图片描述

在这里插入图片描述

复数和自然数
在这里插入图片描述

使用math库来打印出一些常用的值

import math

# Print the value of pi
print ('pi = ', math.pi)

# Print the value of e
print ('e = ', math.e)

# Print the value of square root of 2
print ('sqrt(2) = ', math.sqrt(2))

事实上,这些值记录的是有限的

pi = 3.141592653589793
e = 2.718281828459045
sqrt(2) = 1.4142135623730951

代码2
打印圆周率、 2 \sqrt2 2 和自然常数 e,小数点后 1,000 位数字
Mpmath 是一个任意精度浮点运算库

from mpmath import mp
#设置小数点位数,保留几位有效数字,如果是1的话,就是整数,四舍五入
mp.dps = 1000+1

print('print 1000 digits of pi behind decimal point')
print(mp.pi)

print('print 1000 digits of e behind decimal point')
print(mp.e)

print('print 1000 digits of sqrt(2) behind decimal point')
print(mp.sqrt(2))

判断奇数偶数

num = float(input("Enter a number: "))
#判断是否为整数
if num.is_integer():

    if (num % 2) == 0:
       print("{0} is even ".format(int(num)))
    else:
       print("{0} is odd ".format(int(num)))

else:
    print("{0} is not an integer ".format(num))

两数加减

num1 = 2
num2 = 3

# add two numbers
sum = num1 + num2

# display the computation
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
#两数之差
num1 = 5
num2 = 3

# add two numbers
diff = num1 - num2

# display the computation
print('The difference of {0} and {1} is {2}'.format(num1, num2, diff))



#输入数字
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')

# add two numbers
sum = float(num1) + float(num2)

# display the computation
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

产生序列

import numpy as np
#1到10,产生10个数字
a_i = np.linspace(1,10,10)
print(a_i)
#计算累加
a_i_cumsum = np.cumsum(a_i)
print(a_i_cumsum)

[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
[ 1. 3. 6. 10. 15. 21. 28. 36. 45. 55.]

矩阵向量的表示:

向量的声明和向量的转置

#括号的差异
import numpy as np

# row vector transposed to a column vector
a_row = np.array([[1, 2, 3]])
#1*3
b = a_row.T

b_col = np.array([[1],[2],[3]])
b_col.shape
#3*1
a = b_col.T

取数组矩阵元素的方法

A = np.array([[1, 2, 3],
              [4, 5, 6]])
#所有行,第零列
#保存成行
A_first_col = A[:,0] # saved as one dimension row
#保存成列
#因为列表表示取多个元素,所以即使取一列,也会以二维的形式取出
A_first_col_V2 = A[:,[0]] # saved as a column

A_first_second_col_V2 = A[:,[0,1]] # extract first and second columns

A_first_third_col_V2 = A[:,[0,2]] # extract first and third columns

A_first_row = A[[0],:] # extract first row

A_second_row = A[[1],:] # extract second row

A_second_row_first_col = A[[1],[0]] # i = 2, j = 1

streamlit的绘图

使用

streamlit run Streamlit_Bk3_Ch1_02.py

来运行下面的文件
在这里插入图片描述

from mpmath import mp
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt

with st.sidebar:
    #应用程序侧边栏
    
    #在侧边栏中创建一个滑块,允许用户选择要计算的 π 的小数位数。用户可以选择从 10,000 到 100,000 位,以 10,000 位为步长。
    num_digits = st.slider('Number of decimal digits:',
                           min_value = 10000, 
                           max_value = 100000,
                           step = 10000)
#  mp.dps = num_digits + 2:将 mpmath 库中的小数位数(精度)设置为用户选择的位数加上 2 位(以避免舍入错误)。
mp.dps = num_digits + 2
#pi_digits = mp.pi:计算指定位数的 π。
pi_digits = mp.pi
# st.write(str(pi_digits))
#只保留小数部分
pi_digits = str(pi_digits)[2:]
#转为整数列表
pi_digits_list = [int(x) for x in pi_digits]
# st.write(pi_digits_list)
#转为array数组
pi_digits_array = np.array(pi_digits_list)
#统计数组中每个数字(0-9)出现的次数
counts = np.bincount(pi_digits_array)

#6.创建水平条形图:
fig, ax = plt.subplots()
#绘制水平条形图,x 轴表示每个数字的计数,y 轴表示数字 0-9。条形有浅灰色边缘。
ax.barh(range(10), counts, align = 'center',
        edgecolor = [0.6, 0.6, 0.6])
#隐藏图表的顶部边框和右侧框
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

ax.set_xlabel('Count')
ax.set_ylabel('Digit, 0~9')
plt.yticks(range(10))

st.pyplot(fig)

在这里插入图片描述
这个图也比较好看,尝试画一下.
1024位,也就是说,需要一个[32,32]的数组来存储。

from mpmath import mp
import streamlit as st
import numpy as np
import math as m

import matplotlib.pyplot as plt

# 生成平方数列表
square_numbers = [i ** 2 for i in range(10, 34)]  # 10^2 到 32^2 之间的平方数
# 为了美观设置为正方形的数
with st.sidebar:
    # 应用程序侧边栏

    # 在侧边栏中创建一个滑块,允许用户选择要计算的 π 的小数位数。用户可以选择从 10,000 到 100,000 位,以 10,000 位为步长。
    num_digits = st.select_slider('Number of decimal digits:', options=square_numbers)
# num_digits=100
# 设置高精度计算位数
mp.dps = num_digits + 2
pi_digits = mp.pi
pi_digits = str(pi_digits)[2:]
pi_digits_list = [int(x) for x in pi_digits]
print(len(pi_digits_list))
#因为会多一个,截断,凑整平方
pi_digits_array = np.array(pi_digits_list[:-1])
pi_digits_array.resize(int(m.sqrt(num_digits)),int(m.sqrt(num_digits)))
# pi_digits_array.shape=(int(m.sqrt(num_digits)),int(m.sqrt(num_digits)))
# 绘制热力图
fig, ax = plt.subplots()
#cmap的颜色加上一个_r可以改变颜色的顺序
cax = ax.imshow(pi_digits_array, cmap='RdYlBu_r', interpolation='nearest')# 添加颜色条
#可以禁用interpolation是像素清晰,避免插值后模糊
# 使用 pcolormesh 添加方块边界线
#添加边界线,下面的图没有添加
#ax这两个绘制调用一个即可
#cax = ax.pcolormesh(heatmap_data, cmap='RdYlBu_r', edgecolors='white', linewidths=0.1)



fig.colorbar(cax)

# 设置轴标签
ax.set_xlabel('Next Digit')
ax.set_ylabel('Current Digit')


st.pyplot(fig)

在这里插入图片描述

矩阵的一般类型

在这里插入图片描述

在这里插入图片描述

构造二维矩阵

对角矩阵

import numpy as np

# 创建对角矩阵
diagonal_elements = [1, 2, 3, 4]
diag_matrix = np.diag(diagonal_elements)
print("对角矩阵:\n", diag_matrix)

单位矩阵

import numpy as np

# 创建单位矩阵
size = 4
identity_matrix = np.eye(size)
print("单位矩阵:\n", identity_matrix)

对称矩阵

import numpy as np

# 创建对称矩阵
A = np.array([[1, 2, 3],
              [2, 4, 5],
              [3, 5, 6]])
print("对称矩阵:\n", A)

零矩阵

import numpy as np

# 创建零矩阵
rows, cols = 3, 3
zero_matrix = np.zeros((rows, cols))
print("零矩阵:\n", zero_matrix)

numpy.matrix现在不推荐使用了
声明方式和之前一样,但是再额外套一个np.matrix()
如:np.matrix(np.eye(size))

矩阵的加和运算

四种计算行向量相加方式,推荐使用np来进行矩阵的相加

list1=[1, 2, 3]
list2=[4, 5, 6]
#zip可以形成组
#(1, 4)
#(2, 5)
#(3, 6)
print([x + y for x, y in zip(list1, list2)])
#[5, 7, 9]
#使用lambda进行列表的元素级加法
#lambda x,y: x+y: 这是一个匿名函数(lambda 函数,省略了函数的规范名字,参数名什么的),它接受两个参数 x 和 y,并返回它们的和。list1和list2是传入的参数对象
#map(function, iterable, ...)
#map接收可迭代参数,传递给函数lambda

print(list(map(lambda x,y:x+y, list1, list2)))
#[5, 7, 9]

import numpy as np

x = np.array(list1)
y = np.array(list2)
print(x+y)
#[5 7 9]
print(np.add(list1,list2))
#[5 7 9]

http://www.kler.cn/news/288693.html

相关文章:

  • python-pdf文件加密和解密
  • 评价决策类——层次分析法+数学建模+实战分析
  • spring -- AOP详解
  • QT教程-十六,QT中如何解析JSON
  • Java注解基础入门
  • LiveQing视频点播流媒体RTMP推流服务功能-支持OBS推流摄像机RTMP推流支持无人机RTMP推流解决大疆无人机推流花屏问题完美解决大疆无人机花屏
  • Postgresql表和索引占用空间回收释放(表空间膨胀)
  • NTFS安全权限和文件共享
  • Ajax的$.post(),$.get(),$.ajax 方法请求都是默认异步请求
  • Python | Leetcode Python题解之第390题消除游戏
  • 3D Tiles的4x4的仿射变换矩阵
  • 计算机网络——ARP篇
  • 向沐神学习笔记:GPT,GPT-2,GPT-3 论文精读【论文精读】GPT部分
  • 4G手机智能遥控开关
  • Oracle查询预防解决分母为0的方法
  • 防御网站数据爬取:策略与实践
  • 基于FPGA实现SD NAND FLASH的SPI协议读写
  • 棋类游戏定制开发:步骤详解
  • ET6框架(七)Excel配置工具
  • 【数论 状态机dp】2572. 无平方子集计数
  • c++懒汉式单例模式(Singleton)多种实现方式及最优比较
  • laravel8快速开发简单博客系统(二)
  • HarmonyOS NEXT实战:“相机分段式拍照”性能提升实践
  • 深度学习100问11:什么是one-hot编码
  • Anaconda安装和环境配置教程(深度学习准备)
  • 用SQL语句 对时间进行周期计算week(date,mode)
  • SAP B1 三大基本表单标准功能介绍-物料主数据(下)
  • ClickHouse实时探索与实践 京东云
  • 使用LLaMA-Factory快速训练自己的专用大模型
  • 空间计量 | 似不相关回归SUR