Reputation: 700
Nim language question here. I want to read a series of floats from stdin (this example: 7, 1, 4, 4, nan, 4) and store it in a seq[float]
type. The input may contain NaNs. But I fail to integrate such outliers.
My code:
var
line: TaintedString
timeSeries: seq[float]
while readline(stdin, line) != false:
echo timeSeries
timeSeries.add(parseFloat(line))
The output:
@[]
@[7.0]
@[7.0, 1.0]
@[7.0, 1.0, 4.0]
@[7.0, 1.0, 4.0, 4.0]
@[7.0, 1.0, 4.0, 4.0, nan]
@[nan, nan, nan, nan, nan, nan]
Facing the first NaN, Nim renders all inputs as NaNs. But I want this (last line of output):
@[7.0, 1.0, 4.0, 4.0, nan, 4.0]
How do I solve it correctly in Nim? Documentation says NaNs are supported…
Upvotes: 0
Views: 113
Reputation: 76792
Since you echo timeSeries
before you add the next number, the input of the last line with 4
causes the @[7.0, 1.0, 4.0, 4.0, nan]
and it is guesswork what you did after that to get the final output line. Although I doubt there is a valid reason for anything to set every value in the sequence to NaN
, it might be that what your input triggered a bug.
I have not been able to reproduce your output
with your code (adding the required import strutils
) when entering your sequence followed by another 4
, nan
or empty line (the latter erroring on invalid float).
For easier testing, I put your input in a file input.txt
:
7
1
4
4
nan
4
and ran the following on the latest stable nim (Nim Compiler Version 0.19.4 [Linux: amd64]) as the latest devel nim (Nim Compiler Version 0.19.9 [Linux: amd64]):
import strutils
var
line: TaintedString
timeSeries: seq[float]
echo timeSeries
for line in "input.txt".lines:
timeSeries.add(parseFloat(line.strip))
echo timeSeries
(the .strip
is only there to handle trailing spaces in the input that were a result of cut-and-paste and sloppy editing)
Both compilers output:
@[]
@[7.0]
@[7.0, 1.0]
@[7.0, 1.0, 4.0]
@[7.0, 1.0, 4.0, 4.0]
@[7.0, 1.0, 4.0, 4.0, nan]
@[7.0, 1.0, 4.0, 4.0, nan, 4.0]
compiling with -d:release
did not cause any errors either.
Upvotes: 2