python3 四舍五入实现--简单易用(非round)

Python实现真正的四舍五入 Python 内置函数 round() 部分场景未能实现四舍五入,本文分享了一个 Python 实现真正四舍五入的方法,仅供参考。 阅读详情

round(),四舍六入五平分,无法满足要求,int( )只舍不进也不满足要求。下面使用 decimal 包实现严格四舍五入:

from decimal import Decimal

a = 4.5454545
# 保留整数
int(Decimal(str(a)).quantize(Decimal('0'), rounding='ROUND_HALF_UP'))  # return 5
# 保留一位小数
float(Decimal(str(a)).quantize(Decimal('.0'), rounding='ROUND_HALF_UP')) # return 4.5
# 保留两位小数
float(Decimal(str(a)).quantize(Decimal('.00'), rounding='ROUND_HALF_UP')) # return 4.55
# 保留三位小数
float(Decimal(str(a)).quantize(Decimal('.000'), rounding='ROUND_HALF_UP')) # return 4.545
# 以此类推,保留六位小数
float(Decimal(str(a)).quantize(Decimal('.000000'), rounding='ROUND_HALF_UP')) # return 4.545455

负数也适用,代码是长了点,贵在可以直接用。

python round四舍五入和decimal库精确四舍五入 decimal模块以三个核心概念为中心:十进制数(Decimal)、算术上下文(Context)和信号(Signals十进制数是不可变的,包含符号、系数数字和一个指数。算术上下文定义了精度、舍入规则等。信号用于处理计算中的异常条件。 阅读详情

相关推荐

python 四舍五入

强转int会向下取整 int(2.9),结果为2 四舍五入就用round( )?Python四舍五入的正确打开方式! round( )函数简介 菜鸟教程中介绍到,round() 函数作用就是,返回浮点数x的四舍五入值。 > round( x [, n] ) 参数x,n均为数值表达式,返回值为x的四舍五入值。n为保留的小数位数,不加n则只保留x四舍五入后的整数部分。 >>> round(2.3) 2 >>> round(2....

jacke121的专栏 1万+

不要用python的round函数进行四舍五入

print('2.105:',round(2.105,2),'\n', '2.115:',round(2.115,2),'\n', '2.125:',round(2.125,2),'\n', '2.135:',round(2.135,2),'\n', '2.145:',round(2.145,2),'\n', '2.155:',roun...

qq_32743235的博客 1529

协方差矩阵

对两个类内协方差矩阵进行对角化,可以将它们变换为对角矩阵。这个过程可以通过对每个协方差矩阵进行特征值分解来实现,从而得到它们的特征向量和特征值,进而得到它们的对角矩阵形式。这个过程的意义在于,它可以帮助我们找到一个新的坐标系,使得在这个坐标系下,每个特征之间都是独立的,从而简化了计算。具体来说,当我们使用对角协方差矩阵作为特征向量的坐标系时,它意味着每个特征之间都是相互独立的,从而方便了进一步的分析和处理。在实际应用中,对角化协方差矩阵可以用于降维、特征选择和分类等任务。

m0_55196097的博客 1万+

Python3 里面的四舍五入

Python3 里面的四舍五入

Luxmlb的博客 558

引入 CloudWeGo 后飞书管理后台平台化改造的演进史

飞书管理后台是飞书套件专为企业管理员提供的信息管理平台,它通过引入 Kitex 泛化调用对飞书管理后台进行平台化改造,成为了企业统一数字化管理平台。本文将从三个方面为大家讲解 Kitex 泛化调用在飞书管理后台平台化改造过程中的落地实践。...

weixin_44186218的博客 1769

通俗易通解释SLAM问题的数学描述:运动方程和观测方程

高翔博士在他的《视觉SLAM十四讲》中把SLAM问题的数学描述抽象成了两个数学方程,以下对此做个总结,并且对此做一些通俗易懂的解释: 一、方程的总体形式 作为理性层次的描述,我们引入数学方程来描述SLAM过程,其中第一个方程叫做运动方程、第二个方程叫做观测方程,想象一下我们在研究SLAM的时候肯定需要观测机器人(无人汽车、无人机等都可以统称为机器人)的运动(画面感很强哈哈),这样很容易理解并且记忆这两个方程的名称和意义: 二、变量的含义 我们看到,这两个方程中有大量的英文字母作为变量存在其中,下面介绍一下

weixin_41855010的博客 7139

Python3的四舍五入round()函数坑爹?不,更科学

Python2的round()是四舍五入,而Python3的round()为四舍六入五成双

XerCis的博客 1万+

ue4 角色奔跑/冲刺/蹲下 /蹲走 动作切换蓝图

序列:文章分为4部分: 一、准备工作+简单的蓝图连线 二、编写“行走” 混合空间 三、编写“蹲下”混合空间 四、合成2个动画,设置动画蓝图 —————————————— 一、准备工作 下载“动画初学者包”,添加到项目! 主要文件: 打开BP_playerCharacter,组价——添加组件,找到“摄像机”,“机臂” 没有找到就去其他项目复制过来 ———————————— 手写人物的移动,也可以在...

凉城古梦猫扑街的博客 4872

python3中浮点数float的四舍五入,round跟decimal区别

python3中浮点数float的四舍五入 round 在四舍五入时 round会存在偏差,不推荐使用round # 2.1 2.5 2.61取整时结果是对的 >>> round(2.1) 2 >>> round(2.5) 2 >>> round(2.61) 3 四舍六入五成双 需要舍弃的最后一位是>=6,直接进位 需要舍弃的最后一位是<=4,不进位 需要舍弃的最后一位是5, 判断前面那位是奇数还是偶数,奇数进位 例如 2.215 保留

yuhengshi的博客 1893

网络安全隔离技术解析:单向网闸与双向网闸的核心差异与应用场景

本文深入解析网络安全隔离技术中的单向网闸与双向网闸,详细比较两者的核心差异与应用场景。单向网闸通过物理隔离确保数据单向流动,适用于金融交易等高风险场景;双向网闸则支持严格安检的双向数据交互,常见于医疗、政务等领域。文章还提供了选型建议和技术发展趋势,帮助读者根据安全需求和业务场景选择最适合的网闸解决方案。

weixin_29323365的博客 543

高项备考论文:规划绩效域

高项备考论文:规划绩效域

liuxu324的博客 1137

Python 四舍五入

Python 四舍五入

chenchendiandian的博客 562

一文吃透 ABAP CDS SELECT:语法全景、关联与去重、可运行示例与实战心法

摘要: 本文深入解析ABAP中CDS视图的SELECT语法,重点介绍两种等价写法、关联与路径表达式优化、DISTINCT去重逻辑及WHERE/GROUP BY/HAVING/UNION等子句的应用。通过可运行的业务伙伴角色去重、关联路径查询及多角色筛选示例,演示如何将CDS特性转化为项目实践。强调关联复用性优于传统JOIN,并指出DISTINCT的权限边界与误用场景,帮助开发者从行式思维转向图式数据建模。(150字) 关键词: ABAP CDS、SELECT语法、路径表达式、DISTINCT去重、关联复用

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 399

Python四舍五入及round、Decimal使用

一直为Python的四舍五入感到困惑。机缘情况下,对Python四舍五入及Decimal能否达到我们平常日常生活中所用的的四舍五入进行一些实验和思考。一切以实验数据说话。

czx840624424的博客 5965

NVIDIA GR00T SONIC - 人形机器人强化学习全身控制入门教程(一)

SONIC 是一个类人行为基础模型,它为机器人提供了一套从大规模人类动作数据中学习而来的核心运动技能。与为每个动作单独构建控制器不同,SONIC 将动作追踪作为可扩展的训练任务,因此单一套统一策略即可产生自然的全身运动,并支持多种多样的行为。         🎯 主要特点: 🚶 自然的全身运动(行走、爬行、动态动作) 🎮 支持实时 VR 遥操作 🤖 高级规划与交互的基础 📦 即用型 C++ 推理栈

2506_90492529的博客 856

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

python 如何四舍五入

round()函数—奇进偶舍 奇进偶舍,又称为四舍六入五成双规则、银行进位法。 它是一种计数保留法。从统计学的角度,“奇进偶舍”比“四舍五入”更为精确:在大量运算时,因为舍入后的结果有的变大,有的变小,更使舍入后的结果误差均值趋于零。而不是像四舍五入那样逢五就进位,导致结果偏向大数,使得误差产生积累进而产生系统误差。 “奇进偶舍”使测量结果受到舍入误差的影响降到最低。 但是 这样就会间接的影响到...

doudou_nc的博客 5万+

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

详解python中的round()函数

round()是python自带的一个函数,用于数字的四舍五入。 但是round()的输出结果与Python的版本有关: 在python2中,round(1.0/2.0)=0;在python3中,round(1.0/2.0)=1 $ python Python 2.7.8 (default, Jun 18 2015, 18:54:19) [GCC 4.9.1] on linux2 Typ...

fly_Xiaoma的博客 11万+

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

Python3的四舍五入round()函数

Python2中,round()的结果就是我们所理解的四舍五入,round(1.5)=2,round(2.5)=3。 Python3中,对round()函数有较大改动,例如round(1.5)=2,而round(2.5)却等于2,只有round(2.6)才等于3,这是为什么呢? 原来Python2中的round()是四舍五入,而到了3,round()就变成了“四舍六入五成双”。 这让我想起了大二时候的大物实验,第一节就讲了计数方法,其中印象最深刻的就是这个“四舍六入五成双”,它的作用是让统计数据更公平,降低

python学习者的博客 6255

python四舍五入round_Python四舍五入及round、Decimal使用

Python四舍五入及round、Decimal使用Python四舍五入大法round和Decimal的比对(默认decimal.ROUND_HALF_EVEN)decimal.ROUND_CEILING和decimal.ROUND_FLOORdecimal.ROUND_UP和decimal.ROUND_DOWNdecimal.ROUND_HALF_UP和decimal.ROUND_HALF_DO...

weixin_28893183的博客 1522

python实现小数精确四舍五入

一、现象描述 在机器中浮点数不能精确表达,因为换算成一串1和0后可能是无限位数的,机器已经做出了截断处理。那么在机器中保存的2.675这个数字就比实际数字要小那么一点点。这一点点就导致了它离2.67要更近一点点,所以保留两位小数时就近似到了2.67。 然而,Python使用四舍六入五六双的方法进行取舍,不能精确实现四舍五入。 如下: 无论是round,还是demical都不能很好的进行四舍五入,...

a200822146085的博客 1万+

python3里的四舍五入、numpy包里的四舍五入以及python里格式化输出

一. python3里的四舍五入函数 对于简单的舍入运算,使用内置的 round(value, ndigits) 函数即可。 如果不指定ndigits,则返回整型,否则返回浮点型:比如: print(round(1.23)) # 1 print(type(round(1.23))) # <class 'int'> print(round(1.23, 0)) # 1.0...

EmotionComputer 1万+

【Python 基础教程】彻底解决python round函数的四舍五入不精确的问题

分享了Python中的精确小数计算。decimal模块及round函数的四舍五入经常遇见的问题。

一个非常Cool的人 1万+

Python 的 round() 函数:数值的四舍五入

round()函数是 Python 中的一个内置函数,用于将浮点数近似为指定精度的小数或将浮点数近似为整数。number是要四舍五入的浮点数。ndigits是要保留的小数位数。如果不提供ndigits参数,则round()函数返回最接近的整数。round()函数是 Python 中一个重要且常用的函数,用于对浮点数进行四舍五入。通过合理地应用round()函数,可以提高代码的可读性、可维护性和可理解性。希望本文提供的示例能够帮助大家更好地理解和应用round()函数,从而更好地进行 Python 编程。

GitHub_miao的博客 8262

python语言之round(num, n)小数四舍五入

python round在做小数运算或者四舍五入时怎么避免,数据不精确的问题呢?这就要用到Decimal模块。

西京刀客 2337

python四舍五入(round精度不够,有时不能实现四舍五入)

最近心血来潮,刚复习到折半插入排序时,发现算法的mid,那么当出现奇数时怎么办呢,比如,那么是取1还是2呢?于是我在Python中实验了一下,由于 Python 中浮点数运算结果还是浮点数,因此我用了内置函数来实现小数转整数运算。第一反应就是官方的函数是不是有问题,于是找了几篇博客(参考的一个博客解答,但并没有完全解决>>>2222"""实现四舍五入:param number: 要四舍五入的数字:param ndigits: 要保留的位数:return: 以 float 形式输出"""

森林的博客——在完成之前,似乎总是不可能的~ 1391

python 实现四舍五入,向上取整、向下取整

python四舍五入

qq_38120851的博客 2万+
上一篇: pytorch实战——训练一个简单的分类器(CIFAR10 数据集)
下一篇: leetcode 1024 马尔科夫活动暴力代码
wayne17
博客等级 码龄10年 395粉丝 60原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址