r/ProgrammingLanguages • u/koehr • Jun 05 '26
Discussion Fixing NaN in a compile-to-js lang
Hello community, I'm working on a language that, despite compiling to Javascript, tries to fix some of the nasty quirks JS has. One of them is the whole NaN madness. Because Javascript uses IEEE 754 floating point numbers for everything (except BigInt and after certain binary operations, which makes this even crazier), NaN does never equal NaN. Also comparing any number to NaN always returns false, so a number is neither bigger nor smaller than NaN. That might be fine from a philosophical standpoint, but it is horrible for sorting a list of numbers, for example.
Now I think about how to deal with that. My language could define `NaN == NaN`. JS is doing that as well in certain cases (number keys and sets). But doing so has a long tail of issues, because without extra checks, the language code would behave differently after compilation to JS. But extra checks for every single number comparison? Ooph!
How could I go for this? Is there a good way or am I doomed to include the issues of JS?
36
u/coolreader18 Jun 05 '26
I feel like you could just use bigint if you want integers, no? NaN isn't a "JS problem", it's a feature of floating point numbers, so if you have floats in any language (rust, go, C, Java) they're gonna have NaN.
25
u/kredditacc96 Jun 05 '26
Any language that has floating point will inherit the flaws of IEEE 754. Rust, Python, even Haskell. It is defined by the standard. So I don't think you should deviate from the convention here. As per the principle of least astonishment.
NaN â NaNis intentional and has use cases. Treat them not as values, but as undefined (in a mathematical sense). And undefined can never be equal to undefined.Also, there are more than one bit representation of NaN.
As for keys of maps and sets. It depends on how closely you want your language to follow JavaScript. I assume JS uses the
Object.isequality when doing set keys. Though, if it was me, and if the language was statically typed, I would forbidPartialEqtypes (to borrow Rust terms) to be used as set/map keys.43
u/ChiveSalad Jun 05 '26
Wrong (historically popular) answers only: declare dividing by zero, overflowing, taking a square root of a negative number etc to be undefined behaviour and wash your hands of the matter
2
u/WittyStick Jun 05 '26
You can define a "canonical NaN` which compares equal, and use a fixup for any arithmetic that may return NaN to convert the result to canonical NaN.
2
u/Smalltalker-80 Jun 13 '26 edited Jun 13 '26
My Smalltalk (ST) implementation, SmallJS ( https://small-js.org ) compiles to JS.
It has a full Smalltalk number hierachy supporting: Integer, BigInt, Float, Fraction,
with controlled, automatic conversions to larger types when needed (e.g.: int + float gives float)
(And also classes Date, Character, Point and Rect benefit from this hierarchy)
The source code is here: https://github.com/Small-JS/SmallJS/tree/main/Smalltalk/Core/Magnitude )
.
In only way I saw to bypass JS number 'quirks', was to wrap JS numbers in separate objects,
as instances of JS (ST) classes that inherit from each other. The quirks are handled in the class methods.
There is no specific NaN handling currently, but that can be added easily in this structure.
.
I was worried that this would make the language extremely slow,
but it's allright thanks to the magic of the JS JIT compilers in browsers and Node.js.
Indeed, examples calculating with only small integers are, say, 60x slower,
but as soon as you need BigInts the speed difference is negligable.
The numeric Benchmark example project in the repo shows these results.
.
So you could implement something similar for your lang.
6
u/ChaiTRex Jun 05 '26 edited Jun 05 '26
In Rust, they have a method called
total_cmp. You can click on the Source link on the right side of the header there to see its source code. Note that it doesn't guarantee thatNaN == NaNunless they're generated the same way, as there are multiple different NaN values (they can have different bit patterns), but it does work to allow you to sort things.You can convert from the standard number type to a 64-bit integer by creating an ArrayBuffer and passing that to the constructor of a Float64Array and a BigInt64Array (they should both get the same ArrayBuffer). Then, you can put the two floats into the Float64Array and take the converted values from the BigInt64Array.
1
u/koehr Jun 05 '26
Thank you all for the fruitful discussion. I guess, I will stay on the beaten path and accept the IEEE version. If anyone is interested in the current state of the language spec: https://git.koehr.ing/n/solace
(beware: almost 4k lines in 18 files)
1
u/AtmosphereNo1234 Jun 05 '26
Javascript has https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
Its kind of like SQL where null != null.
1
u/ohkendruid Jun 05 '26
Just be sure to provide the IEEE options as library routines, any time you change one of the built in behaviors.
I agree that == not being true on NaN is a giant headache in programming.
1
u/AustinVelonaut Admiran Jun 05 '26
Are you actively using NaNs for something in your language (NaN-boxing of integers, etc.) or are you compatible with Javascript (ES2020) in that there are just two numeric types: Numbers and BigIntegers? In the later case, NaNs should only occur when a numeric FP operation generates them due to an exception.
6
u/initial-algebra Jun 05 '26 edited Jun 05 '26
I have a strong opinion about floats. If you ask me, the standard number types should be big integers, fixed-point and rational numbers implemented with big integers, and maybe intervals implemented with floats. Machine integers (in this case, integers that fit in a NaN-boxed payload or the various typed arrays) and floats should be considered "low level" or "unsafe" primitives that are mostly not used directly by the average programmer.
Okay, well, you don't have to go to the extreme of implementing intervals, but at least I would wrap floats up in a type that automatically detects and handles various edge cases like signed zeroes (treat them as identical), infinities (clamp back to
MAX/MIN_VALUE) and NaN (throw an exception instead) for general usage. You will also have to adjust operations: for example, dividing by zero should simply throw an exception, since you are treating both signed zeroes as the same "true" zero, and thus returning either signed infinity (which would then be clamped) would be inappropriate.PS: This probably isn't really relevant to OP, but for anyone else interested in my insane opinions, it might also be useful to expose a "sloppy" float type with "fast-math" semantics for cases like graphics programming, where you don't want the overhead of constantly checking for edge cases but you also don't really care about perfect (at least according to the IEEE standard) accuracy. The default float type is the worst of both worlds.
3
u/Exciting_Clock2807 Jun 05 '26
First of all, comparing floats with NaN equal to each other, and not equal to anything including each other - those are two different operations. Each with its own valid use cases. And you totally can have both, under different names.
Now, naming them is an interesting question.
The one where NaN == NaN is false, you probably want to keep compatible with other programming languages. You don't want people to introduce bugs in numeric algorithms when porting code from other languages. So let's stick to `==`/`<=`/`<`.
The second one is more interesting. You could use `===` for equality and `<=>` for 3-value comparison. Or add a set of operators with an extra symbol: `=@=`, `<=@`, `<@`. Or you could have some interface/protocol that requires static function `ComparisonResult compare(T a, T b)`. Or something else.
Keep in mind that NaNs can have payload! There are different possible bit patterns that all are classified as NaN, but they probably would be different values under the second operation! And it would differentiate between `+0` and `-0`!
Second, IEEE 754 defines comparison of floats as 4 value operation. You could have `fcmp()` function returning a 4-value enum. And operators `==`/`<=`/`<` could be returning `Maybe<Bool>` instead of `Bool`. But since rest of the types return `Bool`, this can cause usability problems with generic programming. But feel free to explore and experiment.
Good luck!
3
u/brucejbell sard Jun 05 '26 edited Jun 05 '26
The NaN problem seems similar to the null pointer problem.
At least, you can solve it in a similar way: make sure that there is an "ordered" subtype that excludes NaN's by construction. Provide an easy check to handle NaN if present, or else bind the valid number to its ordered subtype.
Then you can check for NaN once, and bind the result to your ordered subtype for comparison operations like sorting.
As with the null pointer problem: if you don't have a type that excludes the invalid case, the language can't help you -- you have to juggle which values should be valid in your head.
2
u/geocar Jun 07 '26
What does sorting NaN mean to your applications? Is NaN big or small seems the question youâre asking but it isnât clear why. You canât sort a list of numbers when something is not a number, so youâve got to make a choice whether to ignore/elide NaN/null, crash, go wrong, or convert the values to a compatible domain.
Its the same problem with any mixed list of types. I would avoid them and declare them unsortable. This takes some work.
Firstly, for me NaNs represent a lack of measurement, so they are gaps in the time series. If one shows up in a calculator that a user makes (because they write eg rpc=revenue/clicks) then thats not infinity revenue per click, but a failure to measure a click, so i add a small lemma to scalar division to prevent infinity in this case and then discard the lemma because when i sum clicks i dont want a bunch of extra fractions.
This means / and + treat NaN/null differently.
Now: if i sort a list to take the median, i want to remove NaN first, but if i want to sort them for display to users, i want strings. That means sort for my use cases is only defined for regular types, and doesnât have to handle NaN at all.
2
u/Brave-Ad-8201 Jun 07 '26
VocĂȘ pode corrigir, mas nĂŁo de graça. Se sua linguagem diz que
NaN == NaN, entĂŁo==nĂŁo pode compilar direto para===. Vai precisar de uma função auxiliar ou checks especiais. A questĂŁo Ă© decidir se vocĂȘ prefere compatibilidade/performance com JS ou uma semĂąntica mais limpa na sua linguagem. Para ordenação, eu sĂł definiria uma regra explĂcita paraNaN, tipo âsempre no fimâ.1
u/evincarofautumn Jun 07 '26
Nothing says you have to allow all floats everywhere
Just use a more specific type when you know more about what the value can be
A float is undefined or defined, a defined float is infinite or finite, a finite float is subnormal or normal, can get as fine-grained as you like
You only need a runtime check when downcasting, like
Float -> Maybe NumberThat is, the answer to âHow do I use a float as a key in an ordered map?â can be âYou donâtâ â you use a number, or a wrapper that says what ordering you want for NaNs
0
u/[deleted] Jun 05 '26
[deleted] â view deleted comment