目录
个人主页: 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.函数:round
- # 2.功能:用于返回数值经四舍五入规则处理后的值
- # 3.语法:round(number[, ndigits=None])
- # 4.参数:
- # 4-1、number:必须参数,表示需要进行四舍五入规则操作的数值
- # 4-2、ndigits:可选参数,表示小数点后保留的位数,可为任意整数值(正数、零或负数)
- # 4-2-1、若不提供ndigits参数(即只提供number参数),四舍五入取整,返回的值是整数
- # 4-2-2、若设置ndigits=0,则保留0位小数进行四舍五入,返回的值是浮点型
- # 4-2-3、若设置ndigits>0,则四舍五入到指定的小数位
- # 4-2-4、若设置ndigits<0,则对浮点数的整数部分进行四舍五入,参数ndigits用来控制对整数部分的后几位进行四舍五入,小数部分全部清0,返回的值是浮点数;如果传入的整数部分小于参数number的绝对值,则返回0.0
- # 5.返回值:返回四舍五入值
- # 6.说明:使用round()函数四舍五入的规则,如下:
- # 6-1、若保留位数的后一位数字<5,则舍去
- # 6-2、若保留位数的后一位数字>5,则入上去
- # 6-3、若保留位数的后一位数字=5,
- # 6-3-1、且该位数后有数字,则入上去
- # 6-3-2、且该位数后没有数字,根据保留位数的数字的奇偶性处理:若是奇数,则入上去;若是偶数,则舍去
- # 7.示例:
- # 用dir()函数获取该函数内置的属性和方法
- print(dir(round))
- # ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
- # '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__',
- # '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__',
- # '__str__', '__subclasshook__', '__text_signature__']
-
- # 用help()函数获取该函数的文档信息
- help(round)
-
- # 应用一:金融计算
- # 示例1:简单的四舍五入(使用Python内置的round()函数)
- def round_financial_simple(value, decimals=2):
- return round(value, decimals)
- # 示例
- print(round_financial_simple(2.555, 2))
- print(round_financial_simple(2.545, 2))
- # 2.56
- # 2.54
-
- # 示例2:更复杂的金融舍入规则(如果你需要实现特定的舍入规则,例如总是向上舍入或向下舍入)
- def round_financial_up(value, decimals=2):
- multiplier = 10 ** decimals
- return int(value * multiplier + 0.5) / multiplier
- def round_financial_down(value, decimals=2):
- multiplier = 10 ** decimals
- return int(value * multiplier - 0.5) / multiplier if value * multiplier > 0 else int(
- value * multiplier) / multiplier
- # 示例
- print(round_financial_up(2.555, 2)) # 输出: 2.56
- print(round_financial_up(2.545, 2)) # 输出: 2.55
- print(round_financial_down(2.555, 2)) # 输出: 2.55
- print(round_financial_down(2.545, 2)) # 输出: 2.54
- # 2.56
- # 2.55
- # 2.55
- # 2.54
-
- # 示例3:处理货币值(确保结果为整数,因为货币通常没有小数位)
- def round_to_nearest_cent(value):
- return int(round(value * 100))
- # 示例
- print(round_to_nearest_cent(2.555))
- print(round_to_nearest_cent(2.545))
- # 256
- # 254
-
- # 应用二:数据分析和可视化
- # 示例1: 清理DataFrame中的数值列
- import pandas as pd
- # 创建一个示例 DataFrame
- data = {
- 'A': [1.23456, 2.34567, 3.45678],
- 'B': [4.56789, 5.67890, 6.78901],
- 'C': ['str1', 'str2', 'str3'] # 非数值列,不需要清理
- }
- df = pd.DataFrame(data)
- # 清理数值列,保留两位小数
- numeric_cols = ['A', 'B']
- df[numeric_cols] = df[numeric_cols].applymap(lambda x: round(x, 2) if isinstance(x, (int, float)) else x)
- print(df)
- # A B C
- # 0 1.23 4.57 str1
- # 1 2.35 5.68 str2
- # 2 3.46 6.79 str3
-
- # 示例2: 计算平均值并四舍五入
- # 假设我们有一个数值列表
- numbers = [1.23456, 2.34567, 3.45678, 4.56789]
- # 计算平均值并四舍五入到两位小数
- average = round(sum(numbers) / len(numbers), 2)
- print(average)
- # 2.9
-
- # 示例3: 绘制图表前准备数据
- import matplotlib.pyplot as plt
- # 假设我们有一些x和y值,y值需要四舍五入
- x = [1, 2, 3, 4, 5]
- y = [1.23456, 2.34569, 3.45672, 4.56781, 5.67893]
- # 清理y值,保留一位小数
- y_rounded = [round(val, 1) for val in y]
- # 绘制图表
- plt.plot(x, y_rounded, marker='o')
- plt.title('Rounded Data')
- plt.xlabel('X-axis')
- plt.ylabel('Y-axis (rounded)')
- plt.show()
-
- # 示例4: 格式化图表上的标签
- import matplotlib.pyplot as plt
- # 假设我们有一些数据点
- x = [1, 2, 3]
- y = [1.23456, 2.34567, 3.45678]
- # 绘制散点图
- plt.scatter(x, y)
- # 为每个数据点添加标签,并四舍五入到两位小数
- for i, txt in enumerate(y):
- plt.annotate(round(txt, 2), (x[i], y[i]))
- plt.title('Scatter Plot with Rounded Labels')
- plt.xlabel('X-axis')
- plt.ylabel('Y-axis')
- plt.show()
-
- # 应用三:物理模拟
- # 示例1: 简化模拟中的数值
- # 假设我们有一个物理量,比如速度
- speed = 29.9792458
- # 我们可能希望以特定的精度报告这个速度
- reported_speed = round(speed, 2) # 保留两位小数
- print(f"The speed is approximately {reported_speed} m/s.")
- # The speed is approximately 29.98 m/s.
-
- # 示例2: 简化初始条件
- # 假设我们有一个包含初始条件的字典
- initial_conditions = {
- 'position': 1.23456789,
- 'velocity': 2.34567890
- }
- # 我们可以简化这些初始条件以提高模拟的稳定性
- for key, value in initial_conditions.items():
- initial_conditions[key] = round(value, 4) # 保留四位小数
- print(initial_conditions)
- # {'position': 1.2346, 'velocity': 2.3457}
-
- # 示例3: 在迭代过程中控制精度
- # 假设我们有一个模拟函数,该函数在每个时间步更新位置
- def simulate_position(position, velocity, time_step):
- new_position = position + velocity * time_step
- return round(new_position, 6) # 保留六位小数
- # 初始位置和速度
- position = 0.0
- velocity = 1.0
- # 时间步长和模拟时间
- time_step = 0.1
- simulation_time = 1.0
- # 模拟过程
- current_time = 0.0
- while current_time < simulation_time:
- position = simulate_position(position, velocity, time_step)
- current_time += time_step
- print(f"Final position after simulation: {position}")
- # Final position after simulation: 1.1
-
- # 示例4: 绘图时的数据准备
- import matplotlib.pyplot as plt
- # 假设我们有一组模拟结果(时间和位置)
- times = [0.0, 0.1, 0.2, 0.3, 0.4]
- positions = [0.0, 0.10000001, 0.20000004, 0.30000009, 0.40000016]
- # 我们可以简化这些位置值以进行绘图
- rounded_positions = [round(pos, 3) for pos in positions] # 保留三位小数
- # 绘制时间和位置的关系图
- plt.plot(times, rounded_positions, marker='o')
- plt.xlabel('Time(s)')
- plt.ylabel('Position(m)')
- plt.title('Simulated Position vs. Time')
- plt.show()
-
- # 应用四:用户界面显示
- # 示例1: 使用Tkinter和round()显示数值
- import tkinter as tk
- def update_label(rounded_value):
- label.config(text=f"Rounded Value: {rounded_value}")
- # 创建一个Tkinter窗口
- root = tk.Tk()
- root.title("Round() in UI Display")
- # 创建一个标签来显示数值
- label = tk.Label(root, text="Rounded Value: 0.00")
- label.pack()
- # 假设我们有一个需要显示的数值
- original_value = 123.456789
- # 使用round()函数来四舍五入数值到两位小数
- rounded_value = round(original_value, 2)
- # 更新标签以显示四舍五入后的数值
- update_label(rounded_value)
- # 进入Tkinter的主事件循环
- root.mainloop()
-
- # 示例2: 使用按钮来更新显示的数值
- import tkinter as tk
- def update_label():
- global original_value
- # 假设我们每次点击按钮时都增加原始数值
- original_value += 1.0
- rounded_value = round(original_value, 2)
- label.config(text=f"Rounded Value: {rounded_value}")
- # 创建一个Tkinter窗口
- root = tk.Tk()
- root.title("Round() in UI Display with Button")
- # 原始数值
- original_value = 123.456789
- # 创建一个标签来显示数值
- label = tk.Label(root, text=f"Rounded Value: {round(original_value, 2)}")
- label.pack()
- # 创建一个按钮来更新标签
- button = tk.Button(root, text="Update Value", command=update_label)
- button.pack()
- # 进入Tkinter的主事件循环
- root.mainloop()
-
- # 示例3: 使用货币格式化显示数值
- import tkinter as tk
- import locale
- def format_and_update_label(value):
- # 使用round()来确保精度
- rounded_value = round(value, 2)
- # 使用currency函数来格式化数值为货币格式
- locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
- formatted_value = locale.currency(rounded_value, grouping=True)
- label.config(text=formatted_value)
- # 创建一个Tkinter窗口
- root = tk.Tk()
- root.title("Round() and Currency Formatting in UI Display")
- # 创建一个标签来显示数值
- label = tk.Label(root, text="")
- label.pack()
- # 假设我们有一个需要显示的数值
- original_value = 1234.5678
- # 调用函数来更新标签
- format_and_update_label(original_value)
- # 进入Tkinter的主事件循环
- root.mainloop()
-
- # 应用五:统计和概率计算
- # 示例1: 计算平均值并四舍五入
- def calculate_average(numbers):
- return round(sum(numbers) / len(numbers), 2) # 保留两位小数
- numbers = [1.2, 2.3, 3.4, 4.5, 5.6]
- average = calculate_average(numbers)
- print(f"The average is: {average}")
- # The average is: 3.4
-
- # 示例2: 计算正态分布的概率并四舍五入
- from scipy.stats import norm
- def normal_probability(mu, sigma, x):
- return round(norm.cdf(x, mu, sigma), 4) # 保留四位小数
- mu = 0 # 均值
- sigma = 1 # 标准差
- x = 1.96 # 标准正态分布下97.5%的临界值
- probability = normal_probability(mu, sigma, x)
- print(
- f"The probability that a normal random variable with mean {mu} and standard deviation {sigma} is less than or equal to {x} is: {probability}")
-
- # 示例3: 计算二项分布的概率并四舍五入
- from scipy.stats import binom
- def binomial_probability(n, p, k):
- return round(binom.pmf(k, n, p), 4) # 保留四位小数
- n = 10 # 试验次数
- p = 0.5 # 成功概率
- k = 3 # 成功次数
- probability = binomial_probability(n, p, k)
- print(
- f"The probability of getting exactly {k} successes in {n} trials with probability of success {p} is: {probability}")
-
- # 示例4: 计算置信区间并四舍五入
- import math
- def calculate_confidence_interval(data, confidence=0.95):
- n = len(data)
- mean = sum(data) / n
- std_dev = (sum((x - mean) ** 2 for x in data) / (n - 1)) ** 0.5
- margin_of_error = 1.96 * (std_dev / math.sqrt(n)) # 对于95%的置信度,使用z-score为1.96
- lower_bound = round(mean - margin_of_error, 2)
- upper_bound = round(mean + margin_of_error, 2)
- return lower_bound, upper_bound
- data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- lower, upper = calculate_confidence_interval(data)
- print(f"The {calculate_confidence_interval.__defaults__[0] * 100}% confidence interval is ({lower}, {upper})")
- # The 95.0% confidence interval is (3.62, 7.38)
-
- # 应用六:游戏开发
- # 示例1: 计算伤害值并四舍五入
- def calculate_damage(attacker_power, defender_defense):
- # 假设这是一个简单的伤害计算公式
- base_damage = attacker_power - defender_defense
- # 使用round()将伤害值四舍五入到最近的整数
- rounded_damage = round(base_damage)
- return rounded_damage
- attacker_power = 20
- defender_defense = 15
- damage = calculate_damage(attacker_power, defender_defense)
- print(f"The attack did {damage} damage to the enemy.")
- # The attack did 5 damage to the enemy.
-
- # 示例2: 角色位置调整
- def adjust_position(x, y, dx, dy):
- # dx 和 dy 是角色在x和y轴上移动的距离
- new_x = round(x + dx)
- new_y = round(y + dy)
- return new_x, new_y
- character_x = 5.3
- character_y = 3.7
- dx = 2.5
- dy = -1.2
- new_position = adjust_position(character_x, character_y, dx, dy)
- print(f"The character's new position is ({new_position[0]}, {new_position[1]})")
- # The character's new position is (8, 2)
-
- # 示例3: 资源分配
- def allocate_resources(total_resources, unit_count):
- # 假设每个单位应该获得等量的资源
- resources_per_unit = total_resources / unit_count
- # 使用round()确保每个单位获得的资源是整数,并可能剩余一些资源
- allocated_resources = [round(resources_per_unit) for _ in range(unit_count)]
- # 如果总资源不能被单位数整除,可能需要将剩余的资源分配给一些单位
- remaining_resources = total_resources - sum(allocated_resources)
- for i in range(remaining_resources):
- allocated_resources[i] += 1
- return allocated_resources
- total_resources = 100
- unit_count = 7
- allocated = allocate_resources(total_resources, unit_count)
- print(f"The resources are allocated as: {allocated}")
- # The resources are allocated as: [15, 15, 14, 14, 14, 14, 14]
-
- # 应用七:机器学习和深度学习
- # 示例1: 数据预处理时四舍五入特征值
- import pandas as pd
- # 假设你有一个DataFrame 'df' 包含特征 'feature1' 和 'feature2'
- df = pd.DataFrame({
- 'feature1': [1.2345, 2.3456, 3.4567],
- 'feature2': [4.5678, 5.6789, 6.7890]
- })
- # 使用applymap对DataFrame中的所有元素应用round函数
- df_rounded = df.applymap(lambda x: round(x, 2))
- print(df_rounded)
- # df_rounded = df.applymap(lambda x: round(x, 2))
- # feature1 feature2
- # 0 1.23 4.57
- # 1 2.35 5.68
- # 2 3.46 6.79
-
- # 示例2: 四舍五入模型的预测结果
- # 假设你有一个模型 'model' 和一个输入数据 'input_data'
- # 这里以PyTorch为例,但其他库也有类似的预测方法
- import torch
- # 假设你已经加载了模型和数据,并且已经得到了预测结果
- # predictions 是一个tensor,包含模型的预测值
- predictions = torch.tensor([1.2345, 2.3456, 3.4567])
- # 使用round函数对预测结果进行四舍五入
- rounded_predictions = torch.round(predictions * 100) / 100 # 四舍五入到小数点后两位
- # 如果需要转换为numpy数组或Python列表以便进一步处理或报告
- rounded_predictions_numpy = rounded_predictions.numpy()
- rounded_predictions_list = rounded_predictions_numpy.tolist()
- print(rounded_predictions_list)
-
- # 示例3: 评估指标时四舍五入
- # 假设你计算了模型的准确率 'accuracy'
- accuracy = 0.987654321
- # 使用round函数对准确率进行四舍五入到小数点后两位
- rounded_accuracy = round(accuracy, 2)
- print(f"Model accuracy: {rounded_accuracy}")
- # Model accuracy: 0.99
-
- # 应用八:数据库存储
- import sqlite3
- # 连接到SQLite数据库(如果不存在,则创建)
- conn = sqlite3.connect('example.db')
- cursor = conn.cursor()
- # 创建一个表(如果表已存在,则跳过此步骤)
- cursor.execute('''CREATE TABLE IF NOT EXISTS products
- (id INTEGER PRIMARY KEY, name TEXT, price REAL)''')
- # 准备一些要插入的数据,但价格需要四舍五入到小数点后两位
- products = [
- (1, 'Apple', 3.14159),
- (2, 'Banana', 2.71828),
- (3, 'Cherry', 1.61803)
- ]
- # 使用round()函数对数据进行四舍五入,并插入到数据库中
- for product in products:
- id_, name, price = product
- rounded_price = round(price, 2) # 四舍五入到小数点后两位
- cursor.execute("INSERT INTO products (id, name, price) VALUES (?, ?, ?)", (id_, name, rounded_price))
- # 提交事务(确保所有更改都已保存)
- conn.commit()
- # 查询并打印数据库中的数据,以验证插入是否成功且数据已被四舍五入
- cursor.execute("SELECT * FROM products")
- rows = cursor.fetchall()
- for row in rows:
- print(row)
- # 关闭数据库连接
- conn.close()
- # (1, 'Apple', 3.14)
- # (2, 'Banana', 2.72)
- # (3, 'Cherry', 1.62)
-
- # 应用九:配置和设置
- # 假设我们有一个配置字典,其中包含一些浮点数值
- config = {
- 'speed_limit': 120.567, # 速度限制
- 'buffer_size': 1024.25, # 缓冲区大小
- # 其他配置...
- }
- # 在某个处理函数中,我们可能需要根据配置计算某个值,并四舍五入到一定的精度
- def calculate_and_round_value(config_key, precision=2):
- value = config.get(config_key)
- if value is not None and isinstance(value, (int, float)):
- rounded_value = round(value, precision)
- return rounded_value
- else:
- return None # 或者抛出异常,取决于你的错误处理策略
- # 使用示例
- rounded_speed_limit = calculate_and_round_value('speed_limit')
- print(f"Rounded speed limit: {rounded_speed_limit}")
- rounded_buffer_size = calculate_and_round_value('buffer_size')
- print(f"Rounded buffer size: {rounded_buffer_size}")
- # 如果我们想要一个特定的精度
- rounded_to_one_decimal = calculate_and_round_value('speed_limit', precision=1)
- print(f"Rounded speed limit to one decimal: {rounded_to_one_decimal}")
- # Rounded speed limit: 120.57
- # Rounded buffer size: 1024.25
- # Rounded speed limit to one decimal: 120.6
-
- # 应用十:结合其他函数使用
- # 示例1:与数学函数结合使用
- import math
- # 定义一个函数,计算两个数的平均值并四舍五入到小数点后两位
- def rounded_average(a, b):
- average = (a + b) / 2
- return round(average, 2)
- # 示例使用
- print(rounded_average(3.14159, 2.71828))
- # 2.93
-
- # 示例2:与字符串格式化函数结合使用
- # 定义一个函数,将浮点数四舍五入到指定的小数位数,并返回格式化的字符串
- def format_rounded_number(num, decimal_places=2):
- rounded_num = round(num, decimal_places)
- return f"{rounded_num:.{decimal_places}f}"
- # 示例使用
- print(format_rounded_number(3.14159)) # 输出 "3.14"
- print(format_rounded_number(1234.56789, 3)) # 输出 "1234.568"
- # 3.14
- # 1234.568
-
- # 示例3:与自定义函数结合使用(例如,计算圆的面积并四舍五入)
- import math
- # 定义一个函数,计算圆的面积
- def calculate_circle_area(radius):
- return math.pi * (radius ** 2)
- # 定义一个函数,计算圆的面积并四舍五入到小数点后两位
- def rounded_circle_area(radius):
- area = calculate_circle_area(radius)
- return round(area, 2)
- # 示例使用
- print(rounded_circle_area(5))
- # 78.54
-
- # 示例4:与列表推导式结合使用(处理一组数并四舍五入)
- # 定义一个列表,包含一些浮点数
- numbers = [3.14159, 2.71828, 1.61803, 1.41421]
- # 使用列表推导式将列表中的每个数四舍五入到小数点后两位
- rounded_numbers = [round(num, 2) for num in numbers]
- # 打印结果
- print(rounded_numbers)
- # [3.14, 2.72, 1.62, 1.41]
-
- # 示例5:与pandas库结合使用(处理DataFrame中的数据)
- import pandas as pd
- # 创建一个pandas DataFrame
- df = pd.DataFrame({
- 'A': [1.23456, 2.34567, 3.45678],
- 'B': [4.56789, 5.67890, 6.78901]
- })
- # 使用applymap函数将DataFrame中的所有元素四舍五入到小数点后两位
- df_rounded = df.applymap(lambda x: round(x, 2))
- # 打印结果
- print(df_rounded)
- # df_rounded = df.applymap(lambda x: round(x, 2))
- # A B
- # 0 1.23 4.57
- # 1 2.35 5.68
- # 2 3.46 6.79
1-2、VBA:
略,待后补。
2、推荐阅读:
Python算法之旅:Algorithm
Python函数之旅:Functions
个人主页: 神奇夜光杯-CSDN博客



评论记录:
回复评论: