发现一个使用mod函数的bug,大家一起来分析一下,版本:2019b。
13 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
ftnyrgeq
el 25 de Mayo de 2023
Respondida: puxyga
el 25 de Mayo de 2023
我把代码单独摘出来了,直接运行就可以复现这个bug。
当时是需要摘取一段数据中的某一位的数字,采用了逐步取余相减的方法做。在目标位前面数据均为0时会触发这个Bug。代码如下。详细的说明也标注在代码注释里面了。
clear;
rowData = [ 0000011000110000000 ...
0000011000100000000 ...
0000011000010000000];
PHS = rowData/1e6/1e7 - ...
mod(rowData,1e6*1e7)/1e6/1e7; % 截断后13位,输出为[1 1 1]
mod(PHS,1) % 对截断后的数据再对1取余数,结果应该都是0。
% 但是仿真下来第2个元素输出的是1。
bug出现的原因应该和运算精度有关,但是更深一层次的原因我就想不清楚了。大家一起来讨论一下呀。
0 comentarios
Respuesta aceptada
puxyga
el 25 de Mayo de 2023
% 加行代码判断,得知PHS第二个数值实际小于1
PHS<1
% 向上取整避免该问题
mod(ceil(PHS),1)
具体为啥会小于1也不清楚
目前,根据mod函数的帮助文档说明:
b = mod(a,m) returns the remainder after division of a by m, where a is the dividend and m is the divisor. This function is often called the modulo operation, which can be expressed as b = a - m.*floor(a./m). The mod function follows the convention that mod(a,0) returns a.
发现问题出现在m.*floor(a./m),此部分返回的结果是[1 0 1],也是说明了PHS的第二个值是小于1,导致向下取整为0。待高手解答
0 comentarios
Más respuestas (0)
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!