首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

Python-VBA函数之旅-round函数

  • 25-03-03 04:23
  • 3485
  • 11002
blog.csdn.net

目录

一、round函数的常见应用场景

二、round函数使用注意事项

三、如何用好round函数?

1、round函数:

1-1、Python:

1-2、VBA:

 2、推荐阅读:

个人主页: https://blog.csdn.net/ygb_1024?spm=1010.2135.3001.5421

一、round函数的常见应用场景

        round函数在Python中有很多实际应用场景,尤其是在需要进行数值四舍五入或格式化输出的时候,常见的应用场景有:

1、金融计算:在金融领域,经常需要对货币金额进行四舍五入到特定的小数位数,以符合货币单位的精度要求。

2、数据分析和可视化:在数据分析和可视化过程中,经常需要对数据进行预处理,包括四舍五入以减少噪声或简化数据展示。

3、物理模拟:在物理模拟或科学计算中,有时需要限制浮点数的精度以减少计算量或提高性能。

4、用户界面显示:在开发用户界面时,可能需要将数值四舍五入后显示给用户,以提供更简洁易读的信息。

5、统计和概率计算:在处理统计数据和概率计算时,可能需要四舍五入以确保结果的简洁性和可读性。

6、游戏开发: 在游戏开发中,可能需要四舍五入来处理玩家的得分、健康值或其他数值。

7、机器学习和深度学习:在机器学习和深度学习的应用中,经常需要处理浮点数数据,并且可能需要四舍五入来确保数据的一致性和减少计算复杂度。

8、数据库存储:当将浮点数存储到数据库时,可能需要四舍五入到特定的小数位数以减少存储空间的需求或满足特定的数据格式要求。

9、配置和设置: 在处理配置文件或用户设置时,可能需要将输入的四舍五入到特定的范围或格式。

10、结合其他函数使用:round()函数可以与其他数学函数(如sum()、mean()、sqrt()等)结合使用,以在计算过程中进行四舍五入。

        总之,round()函数在需要简化浮点数表示、确保数值精度、满足特定格式要求或进行数值舍入的情况下都是非常有用的。

二、round函数使用注意事项

        在Python中使用round()函数时,需要牢记以下注意事项:

1、浮点数的精度问题:由于计算机内部表示浮点数的方式,有时候round()函数的结果可能不是完全符合预期,这通常发生在需要高精度的金融计算或科学计算中。例如,round(2.675, 2)在某些情况下可能返回`2.67`而不是`2.68`。

2、四舍五入规则:round()函数使用标准的四舍五入规则,即如果小数点后的第三位是5或更大,则第二位加1。但请注意,这种规则可能在一些边缘情况下(例如当需要舍入的数是中间数时)与手动计算的结果有所不同。

3、不要用于安全相关的计算:由于浮点数的精度问题,round()函数不适合用于需要高精度的安全相关计算,如密码学或加密货币交易。

4、负数的四舍五入:对于负数,round()函数也会按照四舍五入的规则进行,但是,由于浮点数的表示方式,有时候结果可能会有些出人意料。例如,`-1.5`在四舍五入到整数时通常会变成`-2`,但`-1.51`可能会变成`-1`。

5、替代方案:如果需要更精确的控制或更可靠的四舍五入行为,可以考虑使用Python的decimal模块,这个模块提供了Decimal类,用于高精度的十进制数运算,包括四舍五入。

6、理解ndigits参数:ndigits参数指定了需要保留的小数位数,如果ndigits是负数,则round()函数会进行整数部分的四舍五入,并保留小数点前指定数量的零,这实际上等同于将数字乘以10的|ndigits|次方,然后进行四舍五入,最后再除以10的|ndigits|次方。

7、返回值类型:round()函数的返回值是一个浮点数,即使输入是一个整数,如果你需要整数结果,可以显式地将结果转换为整数类型(例如,使用int()函数)。

8、避免在循环中连续使用:如果你在一个循环中连续对同一个浮点数进行四舍五入,并且每次都期望得到更精确的结果,那么可能会遇到问题;由于浮点数的精度限制,每次四舍五入都可能会引入新的误差,在这种情况下,最好使用decimal模块或其他高精度数学库。

三、如何用好round函数?

        要用好Python中的round()函数,你需要考虑以下几个方面:

1、了解浮点数的精度问题:浮点数的表示在计算机中不是完全精确的,这可能导致round()函数的结果与预期不符,特别是当数值接近某个整数值的0.5倍时,可能会因为浮点数的表示误差而得到不同的结果。

2、明确舍入规则:round()函数使用标准的四舍五入规则,这意味着它会查看要舍入的小数点后一位的值,如果它是5或更大,则前一位加1;但是,当数值正好位于两个整数之间(例如2.5、3.5等)时,Python 3的行为是向最近的偶数舍入,这被称为“银行家舍入法”(也称为四舍六入五成双)。

3、避免连续舍入:如果你在一个循环或一系列计算中连续使用round()函数,并且每次都在上一步的结果上进行舍入,那么由于浮点数的精度问题,你可能会积累误差,尽量在计算的最后一步进行舍入,或者考虑使用decimal模块来避免这个问题。

4、选择合适的ndigits参数:根据你的需求选择合适的ndigits参数。如果ndigits是正数,则舍入到指定的小数位数;如果ndigits是负数,则对整数部分进行舍入,并保留指定数量的零。

5、检查并验证结果:在使用round()函数后,检查并验证结果是否符合你的期望,特别是在涉及金融或科学计算时,确保结果的准确性至关重要。

6、考虑使用decimal模块:如果你需要更精确的控制或更可靠的舍入行为,可以考虑使用Python的decimal模块,这个模块提供了Decimal类,用于高精度的十进制数运算和舍入。

7、了解Python版本之间的差异:不同版本的Python可能对round()函数的行为有所不同,特别是Python 2和Python 3在舍入到偶数的方式上有所不同,确保你了解你正在使用的Python版本的行为。

8、编写清晰的代码:在代码中使用round()函数时,确保你的代码易于阅读和理解,添加注释以解释为什么使用round()函数以及你选择的ndigits参数的值。

1、round函数:
1-1、Python:
  1. # 1.函数:round
  2. # 2.功能:用于返回数值经四舍五入规则处理后的值
  3. # 3.语法:round(number[, ndigits=None])
  4. # 4.参数:
  5. # 4-1、number:必须参数,表示需要进行四舍五入规则操作的数值
  6. # 4-2、ndigits:可选参数,表示小数点后保留的位数,可为任意整数值(正数、零或负数)
  7. # 4-2-1、若不提供ndigits参数(即只提供number参数),四舍五入取整,返回的值是整数
  8. # 4-2-2、若设置ndigits=0,则保留0位小数进行四舍五入,返回的值是浮点型
  9. # 4-2-3、若设置ndigits>0,则四舍五入到指定的小数位
  10. # 4-2-4、若设置ndigits<0,则对浮点数的整数部分进行四舍五入,参数ndigits用来控制对整数部分的后几位进行四舍五入,小数部分全部清0,返回的值是浮点数;如果传入的整数部分小于参数number的绝对值,则返回0.0
  11. # 5.返回值:返回四舍五入值
  12. # 6.说明:使用round()函数四舍五入的规则,如下:
  13. # 6-1、若保留位数的后一位数字<5,则舍去
  14. # 6-2、若保留位数的后一位数字>5,则入上去
  15. # 6-3、若保留位数的后一位数字=5,
  16. # 6-3-1、且该位数后有数字,则入上去
  17. # 6-3-2、且该位数后没有数字,根据保留位数的数字的奇偶性处理:若是奇数,则入上去;若是偶数,则舍去
  18. # 7.示例:
  19. # 用dir()函数获取该函数内置的属性和方法
  20. print(dir(round))
  21. # ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
  22. # '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__',
  23. # '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__',
  24. # '__str__', '__subclasshook__', '__text_signature__']
  25. # 用help()函数获取该函数的文档信息
  26. help(round)
  27. # 应用一:金融计算
  28. # 示例1:简单的四舍五入(使用Python内置的round()函数)
  29. def round_financial_simple(value, decimals=2):
  30. return round(value, decimals)
  31. # 示例
  32. print(round_financial_simple(2.555, 2))
  33. print(round_financial_simple(2.545, 2))
  34. # 2.56
  35. # 2.54
  36. # 示例2:更复杂的金融舍入规则(如果你需要实现特定的舍入规则,例如总是向上舍入或向下舍入)
  37. def round_financial_up(value, decimals=2):
  38. multiplier = 10 ** decimals
  39. return int(value * multiplier + 0.5) / multiplier
  40. def round_financial_down(value, decimals=2):
  41. multiplier = 10 ** decimals
  42. return int(value * multiplier - 0.5) / multiplier if value * multiplier > 0 else int(
  43. value * multiplier) / multiplier
  44. # 示例
  45. print(round_financial_up(2.555, 2)) # 输出: 2.56
  46. print(round_financial_up(2.545, 2)) # 输出: 2.55
  47. print(round_financial_down(2.555, 2)) # 输出: 2.55
  48. print(round_financial_down(2.545, 2)) # 输出: 2.54
  49. # 2.56
  50. # 2.55
  51. # 2.55
  52. # 2.54
  53. # 示例3:处理货币值(确保结果为整数,因为货币通常没有小数位)
  54. def round_to_nearest_cent(value):
  55. return int(round(value * 100))
  56. # 示例
  57. print(round_to_nearest_cent(2.555))
  58. print(round_to_nearest_cent(2.545))
  59. # 256
  60. # 254
  61. # 应用二:数据分析和可视化
  62. # 示例1: 清理DataFrame中的数值列
  63. import pandas as pd
  64. # 创建一个示例 DataFrame
  65. data = {
  66. 'A': [1.23456, 2.34567, 3.45678],
  67. 'B': [4.56789, 5.67890, 6.78901],
  68. 'C': ['str1', 'str2', 'str3'] # 非数值列,不需要清理
  69. }
  70. df = pd.DataFrame(data)
  71. # 清理数值列,保留两位小数
  72. numeric_cols = ['A', 'B']
  73. df[numeric_cols] = df[numeric_cols].applymap(lambda x: round(x, 2) if isinstance(x, (int, float)) else x)
  74. print(df)
  75. # A B C
  76. # 0 1.23 4.57 str1
  77. # 1 2.35 5.68 str2
  78. # 2 3.46 6.79 str3
  79. # 示例2: 计算平均值并四舍五入
  80. # 假设我们有一个数值列表
  81. numbers = [1.23456, 2.34567, 3.45678, 4.56789]
  82. # 计算平均值并四舍五入到两位小数
  83. average = round(sum(numbers) / len(numbers), 2)
  84. print(average)
  85. # 2.9
  86. # 示例3: 绘制图表前准备数据
  87. import matplotlib.pyplot as plt
  88. # 假设我们有一些x和y值,y值需要四舍五入
  89. x = [1, 2, 3, 4, 5]
  90. y = [1.23456, 2.34569, 3.45672, 4.56781, 5.67893]
  91. # 清理y值,保留一位小数
  92. y_rounded = [round(val, 1) for val in y]
  93. # 绘制图表
  94. plt.plot(x, y_rounded, marker='o')
  95. plt.title('Rounded Data')
  96. plt.xlabel('X-axis')
  97. plt.ylabel('Y-axis (rounded)')
  98. plt.show()
  99. # 示例4: 格式化图表上的标签
  100. import matplotlib.pyplot as plt
  101. # 假设我们有一些数据点
  102. x = [1, 2, 3]
  103. y = [1.23456, 2.34567, 3.45678]
  104. # 绘制散点图
  105. plt.scatter(x, y)
  106. # 为每个数据点添加标签,并四舍五入到两位小数
  107. for i, txt in enumerate(y):
  108. plt.annotate(round(txt, 2), (x[i], y[i]))
  109. plt.title('Scatter Plot with Rounded Labels')
  110. plt.xlabel('X-axis')
  111. plt.ylabel('Y-axis')
  112. plt.show()
  113. # 应用三:物理模拟
  114. # 示例1: 简化模拟中的数值
  115. # 假设我们有一个物理量,比如速度
  116. speed = 29.9792458
  117. # 我们可能希望以特定的精度报告这个速度
  118. reported_speed = round(speed, 2) # 保留两位小数
  119. print(f"The speed is approximately {reported_speed} m/s.")
  120. # The speed is approximately 29.98 m/s.
  121. # 示例2: 简化初始条件
  122. # 假设我们有一个包含初始条件的字典
  123. initial_conditions = {
  124. 'position': 1.23456789,
  125. 'velocity': 2.34567890
  126. }
  127. # 我们可以简化这些初始条件以提高模拟的稳定性
  128. for key, value in initial_conditions.items():
  129. initial_conditions[key] = round(value, 4) # 保留四位小数
  130. print(initial_conditions)
  131. # {'position': 1.2346, 'velocity': 2.3457}
  132. # 示例3: 在迭代过程中控制精度
  133. # 假设我们有一个模拟函数,该函数在每个时间步更新位置
  134. def simulate_position(position, velocity, time_step):
  135. new_position = position + velocity * time_step
  136. return round(new_position, 6) # 保留六位小数
  137. # 初始位置和速度
  138. position = 0.0
  139. velocity = 1.0
  140. # 时间步长和模拟时间
  141. time_step = 0.1
  142. simulation_time = 1.0
  143. # 模拟过程
  144. current_time = 0.0
  145. while current_time < simulation_time:
  146. position = simulate_position(position, velocity, time_step)
  147. current_time += time_step
  148. print(f"Final position after simulation: {position}")
  149. # Final position after simulation: 1.1
  150. # 示例4: 绘图时的数据准备
  151. import matplotlib.pyplot as plt
  152. # 假设我们有一组模拟结果(时间和位置)
  153. times = [0.0, 0.1, 0.2, 0.3, 0.4]
  154. positions = [0.0, 0.10000001, 0.20000004, 0.30000009, 0.40000016]
  155. # 我们可以简化这些位置值以进行绘图
  156. rounded_positions = [round(pos, 3) for pos in positions] # 保留三位小数
  157. # 绘制时间和位置的关系图
  158. plt.plot(times, rounded_positions, marker='o')
  159. plt.xlabel('Time(s)')
  160. plt.ylabel('Position(m)')
  161. plt.title('Simulated Position vs. Time')
  162. plt.show()
  163. # 应用四:用户界面显示
  164. # 示例1: 使用Tkinter和round()显示数值
  165. import tkinter as tk
  166. def update_label(rounded_value):
  167. label.config(text=f"Rounded Value: {rounded_value}")
  168. # 创建一个Tkinter窗口
  169. root = tk.Tk()
  170. root.title("Round() in UI Display")
  171. # 创建一个标签来显示数值
  172. label = tk.Label(root, text="Rounded Value: 0.00")
  173. label.pack()
  174. # 假设我们有一个需要显示的数值
  175. original_value = 123.456789
  176. # 使用round()函数来四舍五入数值到两位小数
  177. rounded_value = round(original_value, 2)
  178. # 更新标签以显示四舍五入后的数值
  179. update_label(rounded_value)
  180. # 进入Tkinter的主事件循环
  181. root.mainloop()
  182. # 示例2: 使用按钮来更新显示的数值
  183. import tkinter as tk
  184. def update_label():
  185. global original_value
  186. # 假设我们每次点击按钮时都增加原始数值
  187. original_value += 1.0
  188. rounded_value = round(original_value, 2)
  189. label.config(text=f"Rounded Value: {rounded_value}")
  190. # 创建一个Tkinter窗口
  191. root = tk.Tk()
  192. root.title("Round() in UI Display with Button")
  193. # 原始数值
  194. original_value = 123.456789
  195. # 创建一个标签来显示数值
  196. label = tk.Label(root, text=f"Rounded Value: {round(original_value, 2)}")
  197. label.pack()
  198. # 创建一个按钮来更新标签
  199. button = tk.Button(root, text="Update Value", command=update_label)
  200. button.pack()
  201. # 进入Tkinter的主事件循环
  202. root.mainloop()
  203. # 示例3: 使用货币格式化显示数值
  204. import tkinter as tk
  205. import locale
  206. def format_and_update_label(value):
  207. # 使用round()来确保精度
  208. rounded_value = round(value, 2)
  209. # 使用currency函数来格式化数值为货币格式
  210. locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
  211. formatted_value = locale.currency(rounded_value, grouping=True)
  212. label.config(text=formatted_value)
  213. # 创建一个Tkinter窗口
  214. root = tk.Tk()
  215. root.title("Round() and Currency Formatting in UI Display")
  216. # 创建一个标签来显示数值
  217. label = tk.Label(root, text="")
  218. label.pack()
  219. # 假设我们有一个需要显示的数值
  220. original_value = 1234.5678
  221. # 调用函数来更新标签
  222. format_and_update_label(original_value)
  223. # 进入Tkinter的主事件循环
  224. root.mainloop()
  225. # 应用五:统计和概率计算
  226. # 示例1: 计算平均值并四舍五入
  227. def calculate_average(numbers):
  228. return round(sum(numbers) / len(numbers), 2) # 保留两位小数
  229. numbers = [1.2, 2.3, 3.4, 4.5, 5.6]
  230. average = calculate_average(numbers)
  231. print(f"The average is: {average}")
  232. # The average is: 3.4
  233. # 示例2: 计算正态分布的概率并四舍五入
  234. from scipy.stats import norm
  235. def normal_probability(mu, sigma, x):
  236. return round(norm.cdf(x, mu, sigma), 4) # 保留四位小数
  237. mu = 0 # 均值
  238. sigma = 1 # 标准差
  239. x = 1.96 # 标准正态分布下97.5%的临界值
  240. probability = normal_probability(mu, sigma, x)
  241. print(
  242. f"The probability that a normal random variable with mean {mu} and standard deviation {sigma} is less than or equal to {x} is: {probability}")
  243. # 示例3: 计算二项分布的概率并四舍五入
  244. from scipy.stats import binom
  245. def binomial_probability(n, p, k):
  246. return round(binom.pmf(k, n, p), 4) # 保留四位小数
  247. n = 10 # 试验次数
  248. p = 0.5 # 成功概率
  249. k = 3 # 成功次数
  250. probability = binomial_probability(n, p, k)
  251. print(
  252. f"The probability of getting exactly {k} successes in {n} trials with probability of success {p} is: {probability}")
  253. # 示例4: 计算置信区间并四舍五入
  254. import math
  255. def calculate_confidence_interval(data, confidence=0.95):
  256. n = len(data)
  257. mean = sum(data) / n
  258. std_dev = (sum((x - mean) ** 2 for x in data) / (n - 1)) ** 0.5
  259. margin_of_error = 1.96 * (std_dev / math.sqrt(n)) # 对于95%的置信度,使用z-score为1.96
  260. lower_bound = round(mean - margin_of_error, 2)
  261. upper_bound = round(mean + margin_of_error, 2)
  262. return lower_bound, upper_bound
  263. data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  264. lower, upper = calculate_confidence_interval(data)
  265. print(f"The {calculate_confidence_interval.__defaults__[0] * 100}% confidence interval is ({lower}, {upper})")
  266. # The 95.0% confidence interval is (3.62, 7.38)
  267. # 应用六:游戏开发
  268. # 示例1: 计算伤害值并四舍五入
  269. def calculate_damage(attacker_power, defender_defense):
  270. # 假设这是一个简单的伤害计算公式
  271. base_damage = attacker_power - defender_defense
  272. # 使用round()将伤害值四舍五入到最近的整数
  273. rounded_damage = round(base_damage)
  274. return rounded_damage
  275. attacker_power = 20
  276. defender_defense = 15
  277. damage = calculate_damage(attacker_power, defender_defense)
  278. print(f"The attack did {damage} damage to the enemy.")
  279. # The attack did 5 damage to the enemy.
  280. # 示例2: 角色位置调整
  281. def adjust_position(x, y, dx, dy):
  282. # dx 和 dy 是角色在x和y轴上移动的距离
  283. new_x = round(x + dx)
  284. new_y = round(y + dy)
  285. return new_x, new_y
  286. character_x = 5.3
  287. character_y = 3.7
  288. dx = 2.5
  289. dy = -1.2
  290. new_position = adjust_position(character_x, character_y, dx, dy)
  291. print(f"The character's new position is ({new_position[0]}, {new_position[1]})")
  292. # The character's new position is (8, 2)
  293. # 示例3: 资源分配
  294. def allocate_resources(total_resources, unit_count):
  295. # 假设每个单位应该获得等量的资源
  296. resources_per_unit = total_resources / unit_count
  297. # 使用round()确保每个单位获得的资源是整数,并可能剩余一些资源
  298. allocated_resources = [round(resources_per_unit) for _ in range(unit_count)]
  299. # 如果总资源不能被单位数整除,可能需要将剩余的资源分配给一些单位
  300. remaining_resources = total_resources - sum(allocated_resources)
  301. for i in range(remaining_resources):
  302. allocated_resources[i] += 1
  303. return allocated_resources
  304. total_resources = 100
  305. unit_count = 7
  306. allocated = allocate_resources(total_resources, unit_count)
  307. print(f"The resources are allocated as: {allocated}")
  308. # The resources are allocated as: [15, 15, 14, 14, 14, 14, 14]
  309. # 应用七:机器学习和深度学习
  310. # 示例1: 数据预处理时四舍五入特征值
  311. import pandas as pd
  312. # 假设你有一个DataFrame 'df' 包含特征 'feature1' 和 'feature2'
  313. df = pd.DataFrame({
  314. 'feature1': [1.2345, 2.3456, 3.4567],
  315. 'feature2': [4.5678, 5.6789, 6.7890]
  316. })
  317. # 使用applymap对DataFrame中的所有元素应用round函数
  318. df_rounded = df.applymap(lambda x: round(x, 2))
  319. print(df_rounded)
  320. # df_rounded = df.applymap(lambda x: round(x, 2))
  321. # feature1 feature2
  322. # 0 1.23 4.57
  323. # 1 2.35 5.68
  324. # 2 3.46 6.79
  325. # 示例2: 四舍五入模型的预测结果
  326. # 假设你有一个模型 'model' 和一个输入数据 'input_data'
  327. # 这里以PyTorch为例,但其他库也有类似的预测方法
  328. import torch
  329. # 假设你已经加载了模型和数据,并且已经得到了预测结果
  330. # predictions 是一个tensor,包含模型的预测值
  331. predictions = torch.tensor([1.2345, 2.3456, 3.4567])
  332. # 使用round函数对预测结果进行四舍五入
  333. rounded_predictions = torch.round(predictions * 100) / 100 # 四舍五入到小数点后两位
  334. # 如果需要转换为numpy数组或Python列表以便进一步处理或报告
  335. rounded_predictions_numpy = rounded_predictions.numpy()
  336. rounded_predictions_list = rounded_predictions_numpy.tolist()
  337. print(rounded_predictions_list)
  338. # 示例3: 评估指标时四舍五入
  339. # 假设你计算了模型的准确率 'accuracy'
  340. accuracy = 0.987654321
  341. # 使用round函数对准确率进行四舍五入到小数点后两位
  342. rounded_accuracy = round(accuracy, 2)
  343. print(f"Model accuracy: {rounded_accuracy}")
  344. # Model accuracy: 0.99
  345. # 应用八:数据库存储
  346. import sqlite3
  347. # 连接到SQLite数据库(如果不存在,则创建)
  348. conn = sqlite3.connect('example.db')
  349. cursor = conn.cursor()
  350. # 创建一个表(如果表已存在,则跳过此步骤)
  351. cursor.execute('''CREATE TABLE IF NOT EXISTS products
  352. (id INTEGER PRIMARY KEY, name TEXT, price REAL)''')
  353. # 准备一些要插入的数据,但价格需要四舍五入到小数点后两位
  354. products = [
  355. (1, 'Apple', 3.14159),
  356. (2, 'Banana', 2.71828),
  357. (3, 'Cherry', 1.61803)
  358. ]
  359. # 使用round()函数对数据进行四舍五入,并插入到数据库中
  360. for product in products:
  361. id_, name, price = product
  362. rounded_price = round(price, 2) # 四舍五入到小数点后两位
  363. cursor.execute("INSERT INTO products (id, name, price) VALUES (?, ?, ?)", (id_, name, rounded_price))
  364. # 提交事务(确保所有更改都已保存)
  365. conn.commit()
  366. # 查询并打印数据库中的数据,以验证插入是否成功且数据已被四舍五入
  367. cursor.execute("SELECT * FROM products")
  368. rows = cursor.fetchall()
  369. for row in rows:
  370. print(row)
  371. # 关闭数据库连接
  372. conn.close()
  373. # (1, 'Apple', 3.14)
  374. # (2, 'Banana', 2.72)
  375. # (3, 'Cherry', 1.62)
  376. # 应用九:配置和设置
  377. # 假设我们有一个配置字典,其中包含一些浮点数值
  378. config = {
  379. 'speed_limit': 120.567, # 速度限制
  380. 'buffer_size': 1024.25, # 缓冲区大小
  381. # 其他配置...
  382. }
  383. # 在某个处理函数中,我们可能需要根据配置计算某个值,并四舍五入到一定的精度
  384. def calculate_and_round_value(config_key, precision=2):
  385. value = config.get(config_key)
  386. if value is not None and isinstance(value, (int, float)):
  387. rounded_value = round(value, precision)
  388. return rounded_value
  389. else:
  390. return None # 或者抛出异常,取决于你的错误处理策略
  391. # 使用示例
  392. rounded_speed_limit = calculate_and_round_value('speed_limit')
  393. print(f"Rounded speed limit: {rounded_speed_limit}")
  394. rounded_buffer_size = calculate_and_round_value('buffer_size')
  395. print(f"Rounded buffer size: {rounded_buffer_size}")
  396. # 如果我们想要一个特定的精度
  397. rounded_to_one_decimal = calculate_and_round_value('speed_limit', precision=1)
  398. print(f"Rounded speed limit to one decimal: {rounded_to_one_decimal}")
  399. # Rounded speed limit: 120.57
  400. # Rounded buffer size: 1024.25
  401. # Rounded speed limit to one decimal: 120.6
  402. # 应用十:结合其他函数使用
  403. # 示例1:与数学函数结合使用
  404. import math
  405. # 定义一个函数,计算两个数的平均值并四舍五入到小数点后两位
  406. def rounded_average(a, b):
  407. average = (a + b) / 2
  408. return round(average, 2)
  409. # 示例使用
  410. print(rounded_average(3.14159, 2.71828))
  411. # 2.93
  412. # 示例2:与字符串格式化函数结合使用
  413. # 定义一个函数,将浮点数四舍五入到指定的小数位数,并返回格式化的字符串
  414. def format_rounded_number(num, decimal_places=2):
  415. rounded_num = round(num, decimal_places)
  416. return f"{rounded_num:.{decimal_places}f}"
  417. # 示例使用
  418. print(format_rounded_number(3.14159)) # 输出 "3.14"
  419. print(format_rounded_number(1234.56789, 3)) # 输出 "1234.568"
  420. # 3.14
  421. # 1234.568
  422. # 示例3:与自定义函数结合使用(例如,计算圆的面积并四舍五入)
  423. import math
  424. # 定义一个函数,计算圆的面积
  425. def calculate_circle_area(radius):
  426. return math.pi * (radius ** 2)
  427. # 定义一个函数,计算圆的面积并四舍五入到小数点后两位
  428. def rounded_circle_area(radius):
  429. area = calculate_circle_area(radius)
  430. return round(area, 2)
  431. # 示例使用
  432. print(rounded_circle_area(5))
  433. # 78.54
  434. # 示例4:与列表推导式结合使用(处理一组数并四舍五入)
  435. # 定义一个列表,包含一些浮点数
  436. numbers = [3.14159, 2.71828, 1.61803, 1.41421]
  437. # 使用列表推导式将列表中的每个数四舍五入到小数点后两位
  438. rounded_numbers = [round(num, 2) for num in numbers]
  439. # 打印结果
  440. print(rounded_numbers)
  441. # [3.14, 2.72, 1.62, 1.41]
  442. # 示例5:与pandas库结合使用(处理DataFrame中的数据)
  443. import pandas as pd
  444. # 创建一个pandas DataFrame
  445. df = pd.DataFrame({
  446. 'A': [1.23456, 2.34567, 3.45678],
  447. 'B': [4.56789, 5.67890, 6.78901]
  448. })
  449. # 使用applymap函数将DataFrame中的所有元素四舍五入到小数点后两位
  450. df_rounded = df.applymap(lambda x: round(x, 2))
  451. # 打印结果
  452. print(df_rounded)
  453. # df_rounded = df.applymap(lambda x: round(x, 2))
  454. # A B
  455. # 0 1.23 4.57
  456. # 1 2.35 5.68
  457. # 2 3.46 6.79
1-2、VBA:
略,待后补。
 2、推荐阅读:

2-1、Python-VBA函数之旅-repr()函数

Python算法之旅:Algorithm

Python函数之旅:Functions

个人主页: 神奇夜光杯-CSDN博客
文章知识点与官方知识档案匹配,可进一步学习相关知识
算法技能树首页概览60891 人正在系统学习中
遨游码海,我心飞扬
微信名片
注:本文转载自blog.csdn.net的神奇夜光杯的文章"https://myelsa1024.blog.csdn.net/article/details/138577630"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2024 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top