{"id":394,"date":"2024-04-17T09:10:18","date_gmt":"2024-04-17T09:10:18","guid":{"rendered":"https:\/\/kurtgrung.com\/blog\/?p=394"},"modified":"2024-06-27T09:37:31","modified_gmt":"2024-06-27T09:37:31","slug":"magic","status":"publish","type":"post","link":"https:\/\/kurtgrung.com\/blog\/magic\/","title":{"rendered":"magic numbers"},"content":{"rendered":"\n<p>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.<\/p>\n\n\n\n<p>Here are some characteristics and considerations regarding magic numbers:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Obscure Meaning<\/strong>: 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.<\/li>\n\n\n\n<li><strong>Code Maintenance Issues<\/strong>: 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.<\/li>\n\n\n\n<li><strong>Reduced Readability<\/strong>: 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.<\/li>\n\n\n\n<li><strong>Debugging Challenges<\/strong>: When encountering unexpected behavior or errors in the code, debugging can be more challenging if the significance of magic numbers is not immediately apparent.<\/li>\n<\/ol>\n\n\n\n<p>To mitigate these issues, it&#8217;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.<\/p>\n\n\n\n<p>For example, instead of using the magic number <code>3.14159<\/code> in calculations involving \u03c0 (pi), it&#8217;s preferable to define a named constant like <code>const PI = 3.14159<\/code>. This not only makes the code more readable but also allows for easier updates or modifications in the future.<\/p>\n\n\n\n<p><br>Magic numbers used in JavaScript for performance optimization:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Fast Inverse Square Root:<\/strong><br>The magic number <code>0x5f3759df<\/code> is used in the Fast Inverse Square Root algorithm to approximate the inverse square root of a floating-point number efficiently.<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>   function fastInverseSqrt(x) {\n       const i = 0x5f3759df - (x &gt;&gt; 1); \/\/ Magic number\n       let y = new Float32Array(1);\n       y&#91;0] = x;\n       let x2 = y&#91;0] * 0.5;\n       y = y&#91;0];\n       const threehalfs = 1.5;\n\n       y = y * (threehalfs - (x2 * y * y));\n       return y;\n   }<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\" start=\"2\">\n<li><strong>Bitwise Operations:<\/strong><br>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.<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>   const M = 0x7fffffff; \/\/ Magic number for modulo\n   function fastModulo(x) {\n       return x &amp; M;\n   }<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\" start=\"3\">\n<li><strong>Hash Functions:<\/strong><br>Magic numbers are sometimes used in hash functions for spreading out input values more evenly across the hash table.<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>   function hashCode(str) {\n       let hash = 0;\n       for (let i = 0; i &lt; str.length; i++) {\n           hash = (hash &lt;&lt; 5) - hash + str.charCodeAt(i);\n           hash |= 0; \/\/ Convert to 32bit integer\n       }\n       return hash;\n   }<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\" start=\"4\">\n<li><strong>Graphics and Image Processing:<\/strong><br>Magic numbers can be used in graphics and image processing algorithms for optimizations such as color space conversions.<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>   function rgbToYUV(r, g, b) {\n       const Y = 0.299 * r + 0.587 * g + 0.114 * b;\n       const U = -0.147 * r - 0.289 * g + 0.436 * b;\n       const V = 0.615 * r - 0.515 * g - 0.100 * b;\n       return &#91;Y, U, V];\n   }<\/code><\/pre>\n\n\n\n<p>These examples demonstrate how magic numbers can be used in JavaScript for performance optimization across various domains. However, it&#8217;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. <br><br><strong>More magic numbers<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Magic Numbers by Kurt Gr\u00fcng \n\n\/\/ Bitwise Operations:\nconst MASK_32 = 0xFFFFFFFF;         \/\/ Mask for 32-bit integers\nconst SIGN_BIT_32 = 0x80000000;     \/\/ Sign bit for 32-bit integers\n\n\/\/ Mathematical:\nconst EULER = 2.71828;              \/\/ Euler's Number\nconst PI = 3.14159;                 \/\/ Pi\n\n\/\/ Physics:\nconst AVOGADRO = 6.02214076e23;     \/\/ Avogadro\nconst C_LIGHT = 299792458;          \/\/ Speed of Light in Meters per Second\nconst G = 6.67430e-11;              \/\/ Gravitational\nconst H_PLANCK = 6.62607015e-34;    \/\/ Planck in Joule-seconds\nconst M_ELECTRON = 9.10938356e-31;  \/\/ Mass of an electron in kilograms\nconst Q_ELECTRON = 1.602176634e-19; \/\/ Elementary charge of an electron in coulombs\n\n\/\/ Miscellaneous:\nconst AU = 0x374079C00;             \/\/ Astronomical Unit\nconst LY = 0x23C34600;              \/\/ Light-Year\nconst MOD = 0x7fffffff;             \/\/ Modulo\nconst F_INV_SQRT = 0x5f3759df;      \/\/ Fast Inverse Square Root\nconst GOLDEN_RATIO = 1.61803398875; \/\/ Golden Ratio\nconst FIBONACCI = 1.61803398875;    \/\/ Fibonacci\nconst MAX_UINT32 = 0xFFFFFFFF;      \/\/ Max 32-bit unsigned integer\nconst NEG_INF = 0xFF800000;         \/\/ Negative Infinity (32-bit float)\nconst NAN = 0x7FC00000;             \/\/ Not-a-Number (32-bit float)\nconst RGBA_TRANSP = 0x00000000;     \/\/ Transparent RGBA\nconst RGBA_WHITE = 0xFFFFFFFF;      \/\/ White RGBA\nconst DEF_PORT = 0x50;              \/\/ Default Port\nconst FLAG_MASK = 0x1F;             \/\/ Flag Mask\nconst MAX_BYTE = 0xFF;              \/\/ Max Byte\nconst NULL_TERM = 0x00;             \/\/ Null Terminator\nconst BMP_SIG = 0x4D42;             \/\/ BMP File Signature\n\n\/\/ Natural:\nconst LN_2 = 0.69314718056;         \/\/ Natural logarithm of 2\nconst SQRT_2 = 1.41421356237;       \/\/ Square root of 2\n\n\/\/ Planck Scale:\nconst L_PLANCK = 1.616255e-35;      \/\/ Planck Length in Meters\nconst T_PLANCK = 5.39116e-44;       \/\/ Planck Time in Seconds\n\n\/\/ Quantum:\nconst E_VOLT = 1.602176634e-19;     \/\/ Electron Volt (eV)\nconst ALPHA = 7.2973525693e-3;      \/\/ Fine-structure\nconst R_BOHR = 5.29177210903e-11;   \/\/ Bohr Radius in Meters\nconst EPSILON_0 = 8.854187817e-12;  \/\/ Vacuum Permittivity in Farads per Meter\nconst MU_0 = 1.25663706212e-6;      \/\/ Vacuum Permeability in Newtons per Ampere squared\n\n\/\/ Thermodynamic:\nconst K_BOLTZMANN = 1.380649e-23;   \/\/ Boltzmann in Joules per Kelvin\nconst R_GAS = 8.31446261815324;     \/\/ Ideal Gas in Joules per Kelvin per Mole\n\n\/\/ Universal:\nconst G_STANDARD = 9.80665;         \/\/ Standard Gravity in Meters per Second squared\nconst M_EARTH = 5.972e24;           \/\/ Mass of the Earth in kilograms\nconst M_SUN = 1.989e30;             \/\/ Mass of the Sun in kilograms<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>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 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[125,8,51],"tags":[],"class_list":["post-394","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-code","category-research"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/kurtgrung.com\/blog\/wp-json\/wp\/v2\/posts\/394","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/kurtgrung.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kurtgrung.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kurtgrung.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/kurtgrung.com\/blog\/wp-json\/wp\/v2\/comments?post=394"}],"version-history":[{"count":5,"href":"https:\/\/kurtgrung.com\/blog\/wp-json\/wp\/v2\/posts\/394\/revisions"}],"predecessor-version":[{"id":458,"href":"https:\/\/kurtgrung.com\/blog\/wp-json\/wp\/v2\/posts\/394\/revisions\/458"}],"wp:attachment":[{"href":"https:\/\/kurtgrung.com\/blog\/wp-json\/wp\/v2\/media?parent=394"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kurtgrung.com\/blog\/wp-json\/wp\/v2\/categories?post=394"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kurtgrung.com\/blog\/wp-json\/wp\/v2\/tags?post=394"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}