Home - Contacts - Terms -

Mi Islita

JavaScript Math FAQs

Frequently Asked Questions (FAQs) on JavaScript Math

Dr. E. Garcia
Mi Islita.com
Email | Last Update: 05/28/05

Topics

About this JavaScript Math FAQs

Conventions Used

Frequently Asked Questions (FAQs)

References

About this JavaScript Math FAQs

Asides programming habits, script optimization deals with the proper use of computational methods and numerical techniques. If you are looking for "please-don't-lecture-me" answers on JavaScript Math, this section is for you. The result of many years of teaching and consulting, this section provides priceless information for

Conventions Used

  1. Optimization: precaching techniques are used.
  2. Presentation: Most script lines have been condensed.
  3. Assumption: Users are familiar with JavaScript and Math.
  4. Nomenclature: When required, a form named "myform" is referenced, unless otherwise stated. A paired labeling system is used. That is, a variable named "z" holds the value of a form field named "z", unless otherwise stated.

Submit a question.

Frequently Asked Questions (FAQs)

How do you...

  1. evaluate how much my monthly mortgage payment will be. Please show me the calculations. I need to know the formula.
    Excellent and practical question. I noticed you don't mention state and 
    federal taxes, predicted rate change per year (usually +/- 0.5%) or to
    compute line of credit and total interests. 
    
    Essentially you ask: "How much will my loan payments be?"
    My ecommerce graduate students are required to write JavaScript 
    calculators using the following instructions. I hope this help.
    
    The general equation is P = PV*IR/(1 - B), where IR is interest rate, 
    expressed as a percentage, PV is the present value or mortgage loan, 
    B is equal to  A ^ -N, N is number of payments and P is monthly 
    payment. A is a dummy term introduced to simplify coding. This term
    is equal to 1 + IR. 
    
    Thus, for the example you describe
    
    PV = 200,000 mortgage loan
    IR = 6.5% annual interest rate
    N = 360 payments
    
    Your monthly payment should be P = $1,264.14 
    (rounded off to two decimal places).
    
    A handy form-based JavaScript calculator can be written with the previous 
    equations and few lines of script. Code some CSS style rules and JavaScript
    vector graphics and voila! Show your client-side graphical calculator to 
    others. Proper changes to the above expressions allows you to create other 
    type of financial calculators. Often, terms of form A = 1 + IR can be found 
    in many compound interest rate, loan, saving and investment calculators.
  2. obtain the root of a number, n, using recursion?
    Use the Mid-Point Displacement Theorem and an infinite loop that 
    will break at a certain tolerance value. The Mid-Point theorem 
    states that the root, R, of a positive number, n, is either within 
    the x < R < n/x or x > R > n/x intervals. Thus, taking averages
    
    R = x = 0.5*(xo + n/xo)
    
    For example, for n = 111, define an initial x value (xo > 0), let 
    say xo = 1 and a tolerance residual, r = 10^-p where p is the number 
    of digits after the decimal place (e.g, p = 7). This will make 
    recursion stepwise-independent. Then do this
    
    var n=111;
    var xo=1;
    var a=Math.abs;
    var p=7;
    var r=Math.pow(10,-p)
    var i=0;
    var t='';
    while (1>0)
    {
    var i=i+1;
    var x=0.5*(xo+n/xo)
    var d=a(x-xo)/x;
    t+=i+' x= '+x.toFixed(p)+' d= '+d.toFixed(p)+'\n';
    if(d<r){break}
    var xo=x;
    }
    alert(t);
    
    Note. This script is meant for illustration purposes of recursive 
    processes. It should not be used with non linear dynamical systems 
    in which, e.g., +/- signs of residuals must be taken into consideration. 
    
    Recursion depends on the initial guessed value (seed) and numerical 
    dynamics of the system under consideration. The optimal seed can be 
    determined using Fixed Point/Attractor Theory. 
    
    Recommended readings:
    
    "A First Course in Chaotic Dynamical Systems"
    Robert L. Devaney; Addison Wesley, 1992.
    
    "An Introduction to Chaotic Dynamical Systems"
    Robert L. Devaney; Addison Wesley, 1989.
    
    During the early 90's (before the Googles and Yahoos of the World) 
    the author autographed me a copy of his book. Thanks, Bob. :)
    
    It's amazing that just recently search engines (Google, MSN) 
    started to improve their algorithms with hardcore non linear 
    dynamics (Chaos Theory). Precisely, this is why the original 
    PageRank model was never a valid framework. See the 
    results now: irrelevant search results everywhere. Their current 
    framework is not any better.
    
  3. convert numbers to strings or strings to numbers?
    Use parseFloat and toString methods, accordingly. Do this
    
    //Number-to-String:
    
    var n=33.33;
    var n=n.toString();
    
    //String-to-Number:
    
    var n="33.33";
    var n=parseFloat(n);
    
    Note. parseInt() method also makes the string-to-number
    conversion but returns integers (without decimal parts).
    Thus, parseFloat() is recommended with high precision 
    calculations in which decimals must be included.
    
  4. convert a numeric value (ie. .74) to have a leading zero (ie. 0.74)?
    By default, JavaScript 1.2 appends a zero
    to decimals without a leading zero,
    as in
    
    alert(.74); //Displays "0.74".
    
    However, to add, let say n = 4 leading 
    zeros to a number such as x = 7.4, do this
    
    var n=4;
    var n=n-1;
    var x=7.4;
    var x=x.toString()
    var z=0;
    do{z="0"+z;}while(--n)
    var x=z+x;
    alert(x); //Displays "00007.4".
    
  5. make a table of even/odd numbers within a given interval (a, b)?
    Define a and b and use two loops, accordingly.
    For example, for a = 3 and b = 10 do this
    
    function ev(x)
    {return (x%2)?false:true;}
    function od(x){return !ev(x);}
    var t='';
    var a=3;
    var b=10;
    t+='<table><tr><td>Even<br>';
    for(var i=a;i<b+1;i++)
    {if(ev(i)==true){t+=i+'<br>';}}
    t+='</td><td>Odd<br>';
    for(var i=a;i<b+1;i++)
    {if(od(i)==true){t+=i+'<br>';}}
    t+='</td></tr></table>';
    document.write(t);
    
  6. add two values to the proper decimal precision?
    JavaScript 1.2 provides straightforward solutions to
    some precision-related computations but not to others.
    Number object solutions are an alternative, however, if
    you prefer not to deal with object-oriented JavaScript, try
    the following.
    
    For data sets given to the same decimal precision (p), 
    e.g., all entries to the same number of decimal places, 
    use the .toFixed(p) JavaScript method.
    
    For example, to add 34440.20 + 21672.20, do this
    
    var v=34440.20+21672.20;
    var v=v.toFixed(2);
    alert(v); //Displays 56112.40
    
    If the data set entries have variable precision,
    (e.g., as in v = 21.2 + 21.20 + 21.200) do this,
    
    1. change all numerical entries to strings.
    2. calculate each string length, L.
    3. for entries with decimal points, substract 1 to the length.
    4. use an if condition to evaluate lowest L.
    5. use the .toFixed(p), where p is the lowest L.
    6. you may need to throw in some pre-processing.
    
    Note. For entries without decimal places, you may need 
    to use the .toPrecision() method, otherwise you will be 
    adding an artificial decimal precision to the computation
    (e.g., the correct precision for the addition operation
    20 + 20.00 is 40, not 40.00). 
    While significant figures are an issue in scientific 
    measurements, they may not be a valid issue in 
    ordinary business transactions. 
    For a CFO 10.15M + 1M = 11.15M, not 11M, right?  :)
    
  7. assign the value of an input field to a variable, z?
    Do this

    var x=document.myform; var z=x.z.value;
  8. assign the value of a computed value, z, to an output field?
    Do this

    var x=document.myform; x.z.value=z;
  9. add an input field value, z, to a quantity, q, then send the sum, s, to an output field?
    Do this

    var x=document.myform; var z=x.z.value; var s=q+parseInt(z); x.s.value=s;
  10. avoid the use of parseInt() in connection with input field values?
    You can use a JavaScript number object. A questionable
    "solution" consists in multiplying the input field value by 1
    before performing the addition.

    var x=document.myform; var z=x.z.value*1; var s=q+z; x.s.value=s;

    Its "beauty" is a matter of taste. We consulted with
    Danny Goodman, author of JavaScript Bible,
    about this "solution". We agree with his observations.
    Although not necessarily "voodoo", this approach is "not
    particularly safe from a data integrity standpoint". He advices:
    "Why avoid parseInt()? It's not only the prescribed way to
    convert a string to a number, but it helps with some of the data
    validation. For instance, if the user enters 123f, parseInt() will
    strip off all non-numeric characters past the last numeric one;
    second, if the user enters f123, parseInt() returns NaN, which
    tells the script right away (if any testing is done with isNaN())
    that there is a problem with the entry."
    Always use parseInt(). To learn more about Danny Goodman's
    work or JavaScript Bible, please visit his authority
    site at http://www.dannyg.com
  11. round off different values, q1, q2, and q3, to the same user-defined number of decimal places, dp, and send the result to different output fields?
    Precache any math method to simplify
    and speed up method calls. Do this

    var x=document.myform; var dp=x.dp.value; var m=Math.pow(10,dp); var r=Math.round; x.q1.value=r(q1*m)/m; x.q2.value=r(q2*m)/m; x.q3.value=r(q3*m)/m; Note: This solution was offered before the .toPrecision(), .toExponential(), and .toFixed() methods were added to the JavaScript core. It can be used with old versions of JavaScript.
  12. raise an input quantity, A, to a user-defined power, n, and send the result to the same output field?
    Redefine A as A=Math.pow(A,n) and do this

    var x=document.myform; var A=x.A.value; var n=x.n.value; var A=Math.pow(A,n); x.A.value=A;

    Add a button and you can emulate the
    power function of a hand calculator.
    Replace n by 1/n to calculate roots.
  13. obtain a random number, r, between two user-defined integer values, m and n, and send the result to an output field?
    Define r as r=m+Math.round(Math.random()*n) and do this

    var x=document.myform; var m=x.m.value; var n=x.n.value; var r=m+Math.round(Math.random()*n) x.r.value=r;
  14. precache constants such as PI or e, the base of natural logarithms?
    Do this

    var pi=Math.PI; var euler=Math.E;
  15. obtain the log of a number, n, at any user-defined base level, b, and send the result, r, to an output field?
    At the time of writing, JavaScript does not
    provide a method for this calculation.
    Define r=Math.log(n)/Math.log(b) and do this

    var x=document.myform; var n=x.n.value; var b=x.b.value; var r=Math.log(n)/Math.log(b); x.r.value=r;

    See our LogIt! script (The Log Transformer) at
    http://www.js-examples.com, a prestigious JavaScript and IT portal.
  16. simplify calculations involving additions and powers?
    Expressions of the form B = (1 + IR)^C
    where IR is interest rate, are found often in
    business and financial calculations. Define A as A = 1 + IR,
    B as B = A^C, and do this

    var x=document.myform; var IR=x.IR.value; var A=1+parseInt(IR); var C=x.C.value; var B=Math.pow(A,C); x.B.value=B;
  17. convert user-defined degrees, d, to radians, rs, and send the result to an output field?
    Do this

    var x=document.myform; var d=x.d.value; var rs=d*Math.PI/180; x.rs.values=rs;

    Modify lines to convert radians to degree.
  18. return the theta part of the polar coordinate (r, theta) that corresponds to the cartesian coordinate (X, Y); that is, the arc tangent of Y/X that is in the range -PI to PI?
    Do this

    var x=document.myform; var X=x.X.value; var Y=x.Y.value; var theta=Math.atan2(X, Y); x.theta.value=theta;

    Result is expressed in radians, not degrees.
  19. return several trigonometric values associated to a user-defined value, n, and send the results to output fields?
    Do this

    var x=document.myform; var n=x.n.value; x.arccosine.value=Math.acos(n); x.arcsine.value=Math.asin(n); x.arctan.value=Math.atan(n); x.cosine.value=Math.cos(n); x.sine.value=Math.sin(n); x.tan.value=Math.tan(n);

    All these methods deal in radians, not degrees.
  20. obtain the smallest integer greater than or equal to a user-defined number (ceil) or the greatest integer less than or equal to a user-defined number (floor)?
    Do this

    var x=document.myform; var n=x.n.value; var nceil=Math.ceil(n); var nfloor=Math.floor(n); x.nceil.value=nceil; x.nfloor.value=nfloor;

    where n is a user-defined quantity.
  21. obtain the larger or smaller of two user-defined numbers, n1 and n2?
    Do this

    var x=document.myform; var n1=x.n1.value; var n2=x.n2.value; var min=Math.min(n1,n2); var max=Math.max(n1,n2); x.min.value=min; x.max.value=max;
  22. raise the euler constant, e, to a user-defined power, n (i.e., e n)?
    Do this

    var x=document.myform; var n=x.n.value; var r=Math.exp(n); x.r.value=r;
  23. obtain the absolute value of a user-defined number, n?
    Do this

    var x=document.myform; var n=x.n.value; var r=Math.abs(n); x.r.value=r;
  24. alert whether a user-defined number, n, is finite or infinite?
    Do this

    var x=document.myform; var n=x.n.value; if(isFinite(n)==true){alert('finite')}else{alert('infinite')}
  25. alert if an invalid number, n, was entered in a form field?
    Do this

    var x=document.myform; var n=x.n.value; if(isNaN(n)==true){alert('That is not a number')}
  26. extract the decimal part of a number?
    Combine parseFloat and parseInt. Do this
    
    var n = 23.75;
    var x=parseFloat(n) - parseInt(n);
    alert('The decimal part of ' +n+' is '+x);
    

    Displays: "The decimal part of 23.75 is 0.75".
  27. perform a decimal-to hexadecimal conversion of a user-defined decimal integer, dec, between 0 to 255?
    Do this

    var x=document.myform; var dec=x.dec.value; var hexChars="0123456789ABCDEF"; if(dec>255){return null} var i=dec % 16; var j=(dec-i)/16; var r="0X"+hexChars.charAt(j)+hexChars.charAt(i); x.r.value=r;

    Adapted from Danny Goodman's JavaScript Bible (1).
  28. obtain the factorial of a number, n?
    At the time of writing, JavaScript does not provide a
    method for calculating factorials. You need to script
    a recursive function. Do this

    function solveit() {var x=document.myform; var n=x.n.value; function factorial(q) {if((q==0)||(q==1)){return 1} else{var qn=(q*factorial(q-1));return qn}} var fn=factorial(n); x.fn.value=fn;}

    Adapted from the Core JavaScript Guide 1.5 (2-4)
    from Developer.Netscape.com site. Here the function
    ("solveit") accepts a user-defined value, n, which is
    then sent to a recursive function named "factorial".
    This new function calculates the factorial of n, fn,
    by looping the q and qn dummy variables and sending the
    result to an output field.
  29. express a number in exponential notation?
    This can be done with JavaScript 1.5 by using the
    toExponential method.

    77.1234.toExponential(4) // displays 7.7123e+1 77.1234.toExponential(2) // displays 7.71e+1 var num=77.1234;num.toExponential(4) // displays 7.7123e+1 var num=77.1234;num.toExponential(2) // displays 7.71e+1

    If the fraction digits argument is omitted, the number
    of digits after the decimal point defaults to the number of
    digits necessary to represent the value uniquely; i.e.

    77.1234.toExponential() // displays 7.71234e+1 var num=77.1234;num.toExponential() // displays 7.71234e+1

    If you use the toExponential method for a numeric literal
    and the numeric literal has no exponent and no decimal
    point, leave a space before the dot that precedes the
    method call to prevent the dot from being interpreted as a
    decimal point. To avoid this, assign the numeric literal to a variable,

    77 .toExponential() // displays 7.7e+1 var num = 77;num.toExponential() // displays 7.7e+1

    If a number has more digits that requested by the fraction digits
    parameter, the number will be rounded to the nearest number
    represented by fraction digits.
    Adapted from the Core JavaScript 1.5 Reference (4).
  30. express a number with absolute precision?
    This can be done with JavaScript 1.5 by using the
    toPrecision method. Do this

    var x=77.1234.toPrecision(3);alert(x); // Displays "77.1" var x=77.1234.toPrecision(5);alert(x); // Displays "77.123" Compare with the toExponential method.
  31. express a number with fixed digits after the decimal place?
    This can be done with JavaScript 1.5 by using the
    toFixed method. Do this

    var x=77.1234.toFixed(3);alert(x); // Displays "77.123" var x=77.1234.toFixed(5);alert(x); // Displays "77.12340" Note that a trailing zero is added to the last result! This resolves the so-called "trailing zero problem" in JavaScript.
  32. compare the toExponential, toPrecision and toFixed methods?
    Do this

    var N=77.1234; var n=3; var x=N.toExponential(n);alert(x); // Displays "7.712e+1" var x=N.toPrecision(n);alert(x); // Displays "77.1" var x=N.toFixed(n);alert(x); // Displays "77.123"
  33. perform integral division (i.e., of d = x/y)?
    Do this

    var x=25; var y=3; var d=x/y; function f() {return(d - x%y/y)} alert(f()); // Displays "8".
  34. remove leading zeros; e.g. convert the "00n" value to "n"?
    Combine parseInt and a radix value, r, such that r > n.
    For instance, for "007" use r = n + 1 = 7 + 1 = 8. Do this

    var x=parseInt("007", 8); alert(x); // Displays "7".
  35. create a user-defined two-dimensional array with c columns and r rows?
    Do this

    var r=4; var c=4; var t=document.write; var a=new Array(r); for(var i=0;i <r;i++) { a[i]=new Array(c); t('<br>'); for(var j=0;j <c;j++) { a[i][j]="["+i+","+j+"]"; t(a[i][j]); } }

    This creates the following array starting at the [0, 0] row-column

    [0,0][0,1][0,2][0,3] [1,0][1,1][1,2][1,3] [2,0][2,1][2,2][2,3] [3,0][3,1][3,2][3,3]

    Adapted from the Core JavaScript Guide 1.5 (3).
  36. divide an interval of length L (from a min to a max value) in n numbers of increments, dx, and display results in an alert window?
    Do this
    
    var n=4;
    var min=5;
    var max=10;
    var L=max-min;
    var dx=L/n;
    var t='';
    t+='Length is '+L+', divided in '+n+' intervals as follow\r\r';
    for(var i=0;i<n;i++)
    {
    var j=i+1;
    t+='Interval '+j+' = '+dx+'\r';
    }
    alert(t);
    
  37. divide an interval of length L (from a min to a max value) at a predefined incremental value, dx, and display results in an alert window?
    Modify previous script to calculate the required  
    number of intervals as n = L/dx. Do this
    var dx=0.50; var min=5; var max=10; var L=max-min; var n=L/dx var t=''; t+='Length is '+L+', divided in '+n+' intervals as follow\r\r'; for(var i=0;i<n;i++) { var j=i+1; t+='Interval '+j+' = '+dx+'\r'; } alert(t)
  38. estimate to a given number of decimal places, dp, the area under the curve, A, of a sine function, y = f(x) = sin(x), within the min=0 to max=PI interval (dx) by approximating it to the total area occupied by n rectangles?
    Do this
    var dp=4; var p=Math.pow(10,dp); var m=Math.round; var n=10; var A=0; var Atotal=0; var min=0; var max=Math.PI; var L=max-min; var dx=L/n; for(var i=0;i<n;i++) { var y=Math.sin(i*dx); A=dx*y; Atotal=Atotal+A; Atotal=m((Atotal)*p)/p; } alert('Area is '+Atotal);

    Note: Area estimates can be improved with Simpson's Rule. Replace the for-loop with a do-while-loop to improve speed. See our JavaScript Optimization FAQs page for details.
  39. generate the Fibonacci series of a number, n?
    Do this
    
    function f(n)
    {
    var s=0;
    if(n==0){return(s);}
    if(n==1){s=s+1;return(s);}
    else{return(f(n-1)+f(n-2));}
    }
    var s='';
    var n=5;
    var n=n+1;
    var k=n;
    do
    {var i=k-n;s=s+'  '+f(i)}
    while(--n);
    alert(s); // Displays "0  1  1  2  3  5" for n=5.
    
    Note. Use small n values with this script; 
    large values may crash your browser.
    
References
  1. Danny Goodman, JavaScript Bible, 3rd Edition,
    Chapter 27, p.571, 1998; IDG Books Worldwide, Inc.
  2. http://devedge.netscape.com/central/JavaScript/
  3. http://devedge.netscape.com/library/manuals/2000/JavaScript/1.5/reference/
  4. http://devedge.netscape.com/library/manuals/2000/JavaScript/1.5/reference/
    number.html#1200968

Thank you for using this site.
Status of the Current Document 
W3C CSS Validation  W3C XHTML Validation
Copyright © 2006 Mi Islita.com -