马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
![](source/plugin/imc_colorcode/images/loading.gif) - (defun mfix (number module retention / temp);;;数值按模数“取整”
- ;;;number 数值,整数或实数
- ;;;module 模数,整数或实数
- ;;;retention 计数保留法(舍入方法),0-四舍五入,1-去尾法,2-进一法,3-四舍六入五成双
- ;;;函数中使用极小数1e-12调整由于浮点数计算出现的偏差,理论上本函数在某些无法预料的情况下可能会出现偏差
- (cond
- ((not (numberp number))
- (princ "\n错误:输入数字必须为整数或实数。")
- (exit)
- )
- ((or (not (numberp module)) (= module 0.0))
- (princ "\n错误:模数必须是整数或实数。")
- (exit)
- )
- ((not (member retention '(0 1 2 3)))
- (princ
- "\n错误:舍入法必须 [0-四舍五入,1-去尾法,2-进一法,3-四舍六入五成双]"
- )
- (exit)
- )
- (t
- (setq temp (/ (float number) module))
- (cond
- ((= retention 0)
- (* (fix (+ temp 0.5 1e-12)) module) ;1e-12本不该有
- )
- ((= retention 1)
- (* (fix temp) module)
- )
- ((= retention 2)
- (* (fix (+ temp 1.0 -1e-15)) module)
- )
- (t
- (if (equal (- temp (fix temp)) 0.5 1e-12)
- (if (= (rem (fix temp) 2) 0)
- (* (fix temp) module)
- (* (fix (+ temp 1.0 -1e-15)) module)
- )
- (* (fix (+ temp 0.5 1e-12)) module)
- )
- )
- )
- )
- )
- )
闲来无事看帖,经常遇到数值保留几位的问题,于是研究一下,整合了几种常见的要求,搞了这么个函数。有兴趣的可以看看,不妨提提意见。
被模数和几种舍入法搞得有点晕,最终是不是有什么不对或遗漏也不清楚了,本想再酝酿一下,又怕搁下来就不想拾起了,所以先贴出来再说。
因为使用了模数概念,所以函数表达方法和以往常见的方法稍有不同,比如保留位数不再是表达为几位,而是和模数位数相同。
例:
1、224.45保留一位小数(四舍五入)
命令: (mfix 224.45 0.1 0)
224.5
2、224.45保留一位小数(去尾法)
命令: (mfix 224.45 0.1 1)
224.4
3、224.45保留一位小数(进一法)
命令: (mfix 224.45 0.1 2)
224.5
4、224.45保留一位小数(四舍六入五成双)
命令: (mfix 224.45 0.1 3)
224.4
5、224.55保留一位小数(四舍六入五成双)
命令: (mfix 224.55 0.1 3)
224.6
6、224.45按0.3模数“取整”
命令: (mfix 224.45 0.3 0)
224.4
7、224.45按15模数“取整”
命令: (mfix 224.45 15 0)
225
8、224.45按3.6模数“取整”
命令: (mfix 224.45 3.6 0)
223.2
|