nim-lang / Nim

Nim is a statically typed compiled systems programming language. It combines successful concepts from mature languages like Python, Ada and Modula. Its design focuses on efficiency, expressiveness, and elegance (in that order of priority).
https://nim-lang.org
Other
16.55k stars 1.47k forks source link

Float to int conversion loses sign #20102

Open rotu opened 2 years ago

rotu commented 2 years ago

Converting a large positive floating point number to an integer can result in a large negative integer.

Example

let l = int.high
echo l
echo l.float.int

https://play.nim-lang.org/#ix=45QL

Current Output

please check whether the problem still exists in git head before posting, see rebuilding the compiler.

9223372036854775807
-9223372036854775808

Expected Output

something like

9223372036854775807
9223372036854775807

or

9223372036854775807
9223372036854774784

Additional Information

nim --version
Nim Compiler Version 1.6.6 [Windows: amd64]
Compiled at 2022-05-05
Copyright (c) 2006-2021 by Andreas Rumpf
demotomohiro commented 2 years ago

I got same result in C lang: https://wandbox.org/permlink/QzZiIKrp1Tv1msxq

It seems converting int to float result in larger value because it is lossy convertion. Converting float value larger than int.high result in negative value because it is undefined behavior? Maybe Nim should throw OverflowDefect when converting float value larger than int.high.

rotu commented 2 years ago

Yeah, it's UB since the floating point is out of range of an int. I think an OverflowDefect would be appropriate. I'm also very surprised that trying to convert Inf and NaN throws an error at compile time but not at runtime.