About the NaN Number

We cannot avoid talking about numbers in programming. Especially about such an important number as NaN. In this article I will try to look at mathematics, numbers, the concept of NaN, and how it works in code.

Mathematics

From this article you will learn:

  • What are floating-point numbers?
  • What is concatenation and how does it work?
  • What does the IEEE 754 standard contain and who prepared it?
  • Why is NaN a number?

Mathematics has always been at the foundation of programming. It is true that programming in high-level languages often does not require us to know complicated algorithms or algebraic identities. We do not need to know integrals or differential calculus. It is enough that we can arrange code into a logical whole that a machine will be able to understand. And that is the whole mystery.

But... mathematics has always been at the foundation of programming. However we look at it, it is mathematics that makes communication possible between us and the computer, or between different electronic devices. Underneath, after all, there are only 0s and 1s arranged in the right order. So we arrive at a simple conclusion: computers communicate using numbers.

Numbers, Numbers, Numbers

The beginnings of number systems go back to antiquity. In Babylonia, digits with values from 1 to 10 were already used, with their value determined by their position in a sequence. You surely also know names such as Pythagoras, Euclid, and Archimedes. They are the ones we associate with some of the first work on numbers.

Numbers are all around us. We use them to express time, the platform number from which our train leaves, the engine capacity of our vehicle, the distance from the office, or the amount of RAM. Without realizing it, we accept numbers, and therefore mathematics in all its glory, into our lives. In his book Humble Pi, Matt Parker argues that we, as humans, have a problem with this field. We are not very good at estimating large numbers, simple calculations, fractions, negative numbers, and many other mathematical concepts until we receive proper training.

How much simpler life would be if we used only whole numbers, and preferably natural numbers. Ideally in the range from 1 to 10, so that the fingers on our hands would be enough to perform calculations. An interesting thought, right?

Unfortunately, it cannot work that way. Without these complicated concepts, so unnatural to our minds, our civilization would not have developed so dynamically. We would not have reached the point where we are now.

Floating-Point Numbers

There is not much to say about whole numbers. They have plenty of uses. Things get more complicated when we want to express that we need something from the interval between one whole number and another. I can already imagine the face of Mr. Mariusz from the neighborhood bakery when I ask for a piece of bread, not 0, but also not 1 whole loaf, roughly 15 cm by eye. Explaining how much bread I need would be an ordeal for both of us. But what if I said: half a loaf, please. We naturally understand what half means.

What remains is how to write that value down. Mathematics allows us to use fractions, meaning parts of a whole. In the example above it would be 1/2. Although classically written fractions are wonderful in their simplicity, they do not quite hold up when they meet reality. The world, after all, needs systematization. So it was decided that if we use the decimal system every day, we will also present fractions as decimal parts. And that is how 1/2 became 0.5.

Numbers written with a decimal separator, a comma in Polish and a dot in English, are floating-point numbers.

Operations on Numbers

Since we already have numbers in our arsenal, it would be good to be able to do something with them. Add, subtract, divide, multiply, calculate the remainder of division, raise to a power, and so on. In programming, we perform all of these mathematical operations. We do not necessarily have to verify the result of these calculations ourselves, but we are, in a way, obliged to understand why we are performing a given operation and what kind of result we can more or less expect. Carelessness in this area can lead to many unpleasant situations, dangerous both to our health and to our wallets. According to estimates, in 2012 JPMorgan Chase lost around 6 billion dollars. The published explanations show that the loss resulted from an error in risk estimation, and more precisely that the error appeared in the formula responsible for those calculations. The formula used the sum of values instead of their average. The result distorted the true picture of investment risk. I do not think we need to add much more.

Again, how much easier it would be if we performed these operations only on numbers. In programming languages we have many different data types available, not only numbers. In some of them it is very easy to add two different types together, for example a string and a number.

Python will not let us perform such an operation. Before doing it, it will check the variable types and block the operation by returning an error.

python
a = 1
b = "abc"

a + b
# TypeError: unsupported operand type(s) for +: 'int' and 'str'

The situation is different in dynamically typed languages such as JavaScript.

js
const a = 1;
const b = "abc";

a + b // "1abc"

JavaScript's mechanism checks the types of the values being added, and if at least one of them is a string, it performs concatenation instead of addition. The same + operator is responsible for both operations. Concatenation is the operation of joining strings together. While doing it, JavaScript converts the joined values to strings. And that is how a small problem is born.

The Lost Type

It may happen that we missed a type somewhere and passed a string to an addition operation instead of a number. We overlooked it and did not catch it in time. The code reached production, and there the user sees the message: "You have NaN PLN left in your account." Something has definitely gone wrong. What is this NaN?

Worth reading on this topic

Pi razy oko. Komedia matematycznych pomyłek

Matt Parker

Pi razy oko. Komedia matematycznych pomyłek

NaN

The Institute of Electrical and Electronics Engineers, or IEEE, is an organization that has been setting standards for electronic devices and computer formats since 1963. One of the standards it published is IEEE 754. It mainly describes binary representation and operations on floating-point numbers. It is a fairly common standard, used in processors and computational software. Within the scope of this standard, the concept of NaN was defined: Not-A-Number. IEEE 754 describes two special values known as NaN: quiet QNaN, or Quiet NaN, and signaling SNaN, or Signaling NaN. Arithmetic operations can be performed on quiet NaNs, because they usually mean an undefined value and do not cause an error. Signaling NaNs most often lead to the operation being interrupted and an exception being thrown. SNaN is often used during variable initialization. If we do not initialize a variable, meaning we do not give it a value, an attempt to use such a variable in a mathematical operation will lead to an error and the operation being stopped.

A Number or Not?

By definition, NaN is a special value that does not represent numbers. Still, in many programming languages the NaN value has a numeric type.

js
typeof NaN; // number

This happens because we get NaN when we perform a mathematical operation whose result cannot be expressed using numbers. That is why, if we try to compare NaN with another NaN, we will always get false. Every NaN will always be a different value.

js
NaN === NaN // false

This is not a peculiarity of JavaScript as a language. It is worth emphasizing that this is a general concept accepted in the programming world.

Summary

I do not want to discuss ways of comparing NaN values in JavaScript in this article. I will probably write a separate post about that someday. What is worth remembering, however, is that NaN and its existence are not specific JavaScript behavior. It is a general concept outlined in the IEEE 754 standard.

We do not need advanced mathematical knowledge to program, but we will not escape mathematics in programming. Numbers surround us in the real world, so it should not surprise us that they are also available in their natural environment: the computer.

Sources

Share this article:

Comments (0)

    No one has posted anything yet, but that means.... you may be the first.

You may be interested in

If this article interested you, check out other materials related to it thematically. Below you will find articles and podcast episodes authored by me, as well as books I recommend that expand on this topic.

Pi razy oko by Matt Parker
Book review
26 June 2022

Pi razy oko

Pan raczy żartować, Panie Feynman? by Richard Feynman
Book review
28 December 2022

Pan raczy żartować, Panie Feynman?

Editor by Maica
Article
2020-07-09

How to Build Your Own Text Editor in the Browser?

A programmer's work is about solving problems. Programming languages are our tools. By using them we can create new solutions, but also new tools. Text editors are definitely such tools. Today we will try to write our own.

Read more

Zapisz się do newslettera

Bądź na bieżąco z nowymi materiałami, ćwiczeniami i ciekawostkami ze świata IT. Dołącz do mnie.