在F#中使用float迭代器列出列表 [英] List comprehensions with float iterator in F#
问题描述
考虑以下代码:
let dl = 9.5 / 11.
let min = 21.5 + dl
let max = 40.5 - dl
let a = [ for z in min .. dl .. max -> z ] // should have 21 elements
let b = a.Length
"a"应具有21个元素,但只有20个元素.缺少"max-dl"值.我知道浮点数并不精确,但是我希望F#可以解决这个问题.如果不是,那为什么F#用float迭代器支持List理解?对我来说,这是漏洞的来源.
"a" should have 21 elements but has got only 20 elements. The "max - dl" value is missing. I understand that float numbers are not precise, but I hoped that F# could work with that. If not then why F# supports List comprehensions with float iterator? To me, it is a source of bugs.
在线试用: http://tryfs.net/snippets/snippet-3H >
推荐答案
转换为小数并查看数字,似乎第21项将超出"最大值:
Converting to decimals and looking at the numbers, it seems the 21st item would 'overshoot' max:
let dl = 9.5m / 11.m
let min = 21.5m + dl
let max = 40.5m - dl
let a = [ for z in min .. dl .. max -> z ] // should have 21 elements
let b = a.Length
let lastelement = List.nth a 19
let onemore = lastelement + dl
let overshoot = onemore - max
那可能是由于let dl = 9.5m / 11.m
中缺乏精度吗?
That is probably due to lack of precision in let dl = 9.5m / 11.m
?
要摆脱这种复合错误,您必须使用另一个数字系统,即Rational. F#Powerpack带有一个BigRational类,可以这样使用:
To get rid of this compounding error, you'll have to use another number system, i.e. Rational. F# Powerpack comes with a BigRational class that can be used like so:
let dl = 95N / 110N
let min = 215N / 10N + dl
let max = 405N / 10N - dl
let a = [ for z in min .. dl .. max -> z ] // Has 21 elements
let b = a.Length
这篇关于在F#中使用float迭代器列出列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!