在 Matlab 中产生随机效应的哈希图
Hash maps producing random effects in Matlab
我目前正在 matlab 中开发一个解决方案,该解决方案需要使用哈希映射作为生成可缩放数据结构的一种方式(就我的问题而言并不重要)。
我有一个 hashmap 定义为
var_hash = containers.Map;
new_array = arr0;
%var_hash = {'foo':arr1,'baz':arr2,'bar':arr3}
var_hash_keys = var_hash.keys();
for i = 1:length(var_hash_keys);
key = var_hash_keys{i};
new_array = new_array + var_hash(key);
end
现在我遇到的问题似乎是简单地添加数组
arr0 + arr1 + arr2 + arr3 != new_array
这是我的严重错误,即糟糕的编程,还是有什么可疑的事情发生?
不过,考虑到要添加的数组相对较少,我已经克服了这一点并以蛮力的方式完成了它,但我想了解我做错了什么。
目前还不完全清楚你的问题是什么 - 但我假设你所观察到的只是 浮点 加法不是精确关联的,因为中间四舍五入。来自 http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html :
Another grey area concerns the interpretation of parentheses. Due to roundoff errors, the associative laws of algebra do not necessarily hold for floating-point numbers. For example, the expression (x+y)+z has a totally different answer than x+(y+z) when x = 10^{30}, y = -10^{30} and z = 1 (it is 1 in the former case, 0 in the latter). The importance of preserving parentheses cannot be overemphasized.
我目前正在 matlab 中开发一个解决方案,该解决方案需要使用哈希映射作为生成可缩放数据结构的一种方式(就我的问题而言并不重要)。
我有一个 hashmap 定义为
var_hash = containers.Map;
new_array = arr0;
%var_hash = {'foo':arr1,'baz':arr2,'bar':arr3}
var_hash_keys = var_hash.keys();
for i = 1:length(var_hash_keys);
key = var_hash_keys{i};
new_array = new_array + var_hash(key);
end
现在我遇到的问题似乎是简单地添加数组
arr0 + arr1 + arr2 + arr3 != new_array
这是我的严重错误,即糟糕的编程,还是有什么可疑的事情发生?
不过,考虑到要添加的数组相对较少,我已经克服了这一点并以蛮力的方式完成了它,但我想了解我做错了什么。
目前还不完全清楚你的问题是什么 - 但我假设你所观察到的只是 浮点 加法不是精确关联的,因为中间四舍五入。来自 http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html :
Another grey area concerns the interpretation of parentheses. Due to roundoff errors, the associative laws of algebra do not necessarily hold for floating-point numbers. For example, the expression (x+y)+z has a totally different answer than x+(y+z) when x = 10^{30}, y = -10^{30} and z = 1 (it is 1 in the former case, 0 in the latter). The importance of preserving parentheses cannot be overemphasized.