Explore my works and
side projects  here

Research, Design & Development.

Magic numbers, in the context of computer programming, are constants or numeric values that are directly embedded into the code without explanation of their meaning or significance. These numbers are typically used to control the behavior of algorithms, formulas, or specific program functionalities. However, they lack descriptive names or comments to clarify their purpose, making the code less readable and more prone to errors or misunderstandings.

Here are some characteristics and considerations regarding magic numbers:

  1. Obscure Meaning: Magic numbers often lack clear documentation or contextual information, making it challenging for other developers (or even the original author) to understand their purpose or significance.
  2. Code Maintenance Issues: When magic numbers are scattered throughout the codebase, modifying or updating them can become cumbersome and error-prone, especially if their meaning is not obvious.
  3. Reduced Readability: Without descriptive names or comments, magic numbers can obscure the intent of the code and make it difficult for others to comprehend the logic behind specific calculations or decisions.
  4. Debugging Challenges: When encountering unexpected behavior or errors in the code, debugging can be more challenging if the significance of magic numbers is not immediately apparent.

To mitigate these issues, it’s generally recommended to avoid using magic numbers in favor of named constants or variables that convey their purpose and meaning more clearly. By assigning meaningful names to constants and documenting their usage, developers can improve the readability, maintainability, and overall quality of their code.

For example, instead of using the magic number 3.14159 in calculations involving π (pi), it’s preferable to define a named constant like const PI = 3.14159. This not only makes the code more readable but also allows for easier updates or modifications in the future.


Magic numbers used in JavaScript for performance optimization:

  1. Fast Inverse Square Root:
    The magic number 0x5f3759df is used in the Fast Inverse Square Root algorithm to approximate the inverse square root of a floating-point number efficiently.
   function fastInverseSqrt(x) {
       const i = 0x5f3759df - (x >> 1); // Magic number
       let y = new Float32Array(1);
       y[0] = x;
       let x2 = y[0] * 0.5;
       y = y[0];
       const threehalfs = 1.5;

       y = y * (threehalfs - (x2 * y * y));
       return y;
   }
  1. Bitwise Operations:
    Magic numbers are often used in conjunction with bitwise operations for various optimizations. For example, masking with a magic number can be used to efficiently calculate modulo operations.
   const M = 0x7fffffff; // Magic number for modulo
   function fastModulo(x) {
       return x & M;
   }
  1. Hash Functions:
    Magic numbers are sometimes used in hash functions for spreading out input values more evenly across the hash table.
   function hashCode(str) {
       let hash = 0;
       for (let i = 0; i < str.length; i++) {
           hash = (hash << 5) - hash + str.charCodeAt(i);
           hash |= 0; // Convert to 32bit integer
       }
       return hash;
   }
  1. Graphics and Image Processing:
    Magic numbers can be used in graphics and image processing algorithms for optimizations such as color space conversions.
   function rgbToYUV(r, g, b) {
       const Y = 0.299 * r + 0.587 * g + 0.114 * b;
       const U = -0.147 * r - 0.289 * g + 0.436 * b;
       const V = 0.615 * r - 0.515 * g - 0.100 * b;
       return [Y, U, V];
   }

These examples demonstrate how magic numbers can be used in JavaScript for performance optimization across various domains. However, it’s important to note that while they can lead to performance gains, they can also make code less readable and harder to maintain if not properly documented.

More magic numbers

// Magic Numbers by Kurt Grüng 

// Bitwise Operations:
const MASK_32 = 0xFFFFFFFF;         // Mask for 32-bit integers
const SIGN_BIT_32 = 0x80000000;     // Sign bit for 32-bit integers

// Mathematical:
const EULER = 2.71828;              // Euler's Number
const PI = 3.14159;                 // Pi

// Physics:
const AVOGADRO = 6.02214076e23;     // Avogadro
const C_LIGHT = 299792458;          // Speed of Light in Meters per Second
const G = 6.67430e-11;              // Gravitational
const H_PLANCK = 6.62607015e-34;    // Planck in Joule-seconds
const M_ELECTRON = 9.10938356e-31;  // Mass of an electron in kilograms
const Q_ELECTRON = 1.602176634e-19; // Elementary charge of an electron in coulombs

// Miscellaneous:
const AU = 0x374079C00;             // Astronomical Unit
const LY = 0x23C34600;              // Light-Year
const MOD = 0x7fffffff;             // Modulo
const F_INV_SQRT = 0x5f3759df;      // Fast Inverse Square Root
const GOLDEN_RATIO = 1.61803398875; // Golden Ratio
const FIBONACCI = 1.61803398875;    // Fibonacci
const MAX_UINT32 = 0xFFFFFFFF;      // Max 32-bit unsigned integer
const NEG_INF = 0xFF800000;         // Negative Infinity (32-bit float)
const NAN = 0x7FC00000;             // Not-a-Number (32-bit float)
const RGBA_TRANSP = 0x00000000;     // Transparent RGBA
const RGBA_WHITE = 0xFFFFFFFF;      // White RGBA
const DEF_PORT = 0x50;              // Default Port
const FLAG_MASK = 0x1F;             // Flag Mask
const MAX_BYTE = 0xFF;              // Max Byte
const NULL_TERM = 0x00;             // Null Terminator
const BMP_SIG = 0x4D42;             // BMP File Signature

// Natural:
const LN_2 = 0.69314718056;         // Natural logarithm of 2
const SQRT_2 = 1.41421356237;       // Square root of 2

// Planck Scale:
const L_PLANCK = 1.616255e-35;      // Planck Length in Meters
const T_PLANCK = 5.39116e-44;       // Planck Time in Seconds

// Quantum:
const E_VOLT = 1.602176634e-19;     // Electron Volt (eV)
const ALPHA = 7.2973525693e-3;      // Fine-structure
const R_BOHR = 5.29177210903e-11;   // Bohr Radius in Meters
const EPSILON_0 = 8.854187817e-12;  // Vacuum Permittivity in Farads per Meter
const MU_0 = 1.25663706212e-6;      // Vacuum Permeability in Newtons per Ampere squared

// Thermodynamic:
const K_BOLTZMANN = 1.380649e-23;   // Boltzmann in Joules per Kelvin
const R_GAS = 8.31446261815324;     // Ideal Gas in Joules per Kelvin per Mole

// Universal:
const G_STANDARD = 9.80665;         // Standard Gravity in Meters per Second squared
const M_EARTH = 5.972e24;           // Mass of the Earth in kilograms
const M_SUN = 1.989e30;             // Mass of the Sun in kilograms

Tags