Results 1 to 8 of 8

Thread: Long division in javascript

  1. #1
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Long division in javascript

    Ok, for some reason in computers, internal calculators cut of after about 21 digits. It's when you start getting the +e23 at the end of an equation.

    I was curious if there is a possible (and simple) way to do long division through javascript?

    I just found out this is * 10^x. Still though, long division?
    document.write is document.wrong

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Division in javascript is with a slash:

    Code:
    12/2
    which equals 6. It can handle large numbers with or without long fractional decimals for input numbers and/or the result. But there are some cases, under some OS's where it might give the wrong answer. If the result is a really big number or a really small one, you may get an expression as the result instead of an integer or a floating point number. Generally this is still a number though, like if you want to perform further Math operations on it.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by jscheuer1 View Post
    Division in javascript is with a slash:

    Code:
    12/2
    which equals 6. It can handle large numbers with or without long fractional decimals for input numbers and/or the result. But there are some cases, under some OS's where it might give the wrong answer. If the result is a really big number or a really small one, you may get an expression as the result instead of an integer or a floating point number. Generally this is still a number though, like if you want to perform further Math operations on it.
    Thanks jscheuer,

    I should have been more clear about the type of division I was attempting to accomplish. I would use 12/6 if I needed a simple division, but I am talking more like 5437890578349789057348920543782954372895034728905437895437890789342689054382905623467895234678543256785463278546237758432567852381543215432789504378290543568574 532908990605478905436789543267895340/10.

    I know it seems ridiculous, but I essentially will probably have to engineer a long/step division system that works because I also need to utilize the actual returned string value (no +e40 at the end of the returned value)

    Back to the 5th grade math books perhaps...
    Last edited by Falkon303; 05-26-2011 at 09:05 PM.
    document.write is document.wrong

  4. #4
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,164
    Thanks
    265
    Thanked 690 Times in 678 Posts

    Default

    What is your purpose? This is unrelated to long division. I think it would be the case with anything, even just typing in a long number and then displaying it. What you may want to try is converting an integer (or other number type) to a string and displaying it that way, rather than displaying it as a number that will get automatically formatted using that "e" notation.

    As John says, even if it displays that way it's still an accurate number. It just displays differently (but that means the same value-- it's equivalent, just in a different format). So you can do other math or whatever else you need.


    Also, I would recommend that if you need accurate advanced math you should not be using Javascript. It will be fine to some extent, but in the most extreme cases it will vary by browser as John said. To avoid that, use a serverside language like PHP and it will be consistent for everyone and you can test to be sure. Having inaccurate math (potentially) isn't helpful, so relying on possibly variable Javascript in different browsers doesn't seem like the best idea.
    Daniel - Freelance Web Design | <?php?> | <html>| español | Deutsch | italiano | português | català | un peu de français | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

  5. #5
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by djr33 View Post
    What is your purpose? This is unrelated to long division. I think it would be the case with anything, even just typing in a long number and then displaying it. What you may want to try is converting an integer (or other number type) to a string and displaying it that way, rather than displaying it as a number that will get automatically formatted using that "e" notation.

    As John says, even if it displays that way it's still an accurate number. It just displays differently (but that means the same value-- it's equivalent, just in a different format). So you can do other math or whatever else you need.


    Also, I would recommend that if you need accurate advanced math you should not be using Javascript. It will be fine to some extent, but in the most extreme cases it will vary by browser as John said. To avoid that, use a serverside language like PHP and it will be consistent for everyone and you can test to be sure. Having inaccurate math (potentially) isn't helpful, so relying on possibly variable Javascript in different browsers doesn't seem like the best idea.
    Thanks for the reply,

    I research mathematics as a hobby, and also prime numbers.

    The problem is that php returns INF as well if a number string is over a certain length, so I essentially am looking for a new way to divide numbers, or a program that can handle number strings > 256 in length, or a way to script in a division system that could systematically return a division result.
    document.write is document.wrong

  6. #6
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    This ended up intriguing me. Here's something you may or may not find useful:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>Scientific Notation to String Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">
    
    function exp2string(num){
    	num = num - 0;
    	var numStr = num.toString(10), re = exp2string.re;
    	if(!re[0].test(numStr) || typeof num !== 'number' || isNaN(num)){
    		alert((typeof num !== 'number' || isNaN(num)? 'exp2string requires a number as input' : 'exp2string requires a number in scientific notation') +
    		'. Returning ' + (isNaN(num)? 'NaN (Not a Number)' : 'Input') + '.');
    		return num;
    	}
    	var numAr = num.toString(10).split(re[3]), result;
    	numAr[0] = numAr[0].replace(re[1], '');
    	if(re[2].test(numAr[1])){
    		result = '0.';
    		numAr[1] = numAr[1] * -1 - 2;
    		for (var i = numAr[1]; i > -1; --i){
    			result += '0';
    		}
    		result += numAr[0];
    	} else {
    		result = numAr[0];
    		numAr[1] = numAr[1] - numAr[0].length;
    		for (var i = numAr[1]; i > -1; --i){
    			result += '0';
    		}
    	}
    		return result;
    }
    exp2string.re = [/^\d\.\d+e[-+]\d+$/i, /\./, /-/, /e/i];
    
    </script>
    <style type="text/css">
    body {
    	color: #000;
    	background-color: #fff;
    	font: normal 85% verdana, arial, sans-serif;
    }
    #strNote {
    	vertical-align: top;
    }
    </style>
    </head>
    <body>
    <form action="#" onsubmit="return false;">
    Input Scientific Notation (#.#e+/-#): <input size=30 id="sciNote" type="text" value="3.6778967343747667e-196"><br>
    <script type="text/javascript">
    /* <![CDATA[ */
    document.write('Result: <textarea id="strNote" cols="50" rows="1" wrap="off" readonly><\/textarea><br>');
    /* ]]> */
    </script>
    <input type="button" value="Go" onclick="document.getElementById('strNote').value = exp2string(document.getElementById('sciNote').value);"><br>
    <input type="button" value="Check Equality" onclick="alert(document.getElementById('strNote').value - 0 == document.getElementById('sciNote').value - 0);"><br>
    <input type="reset" value="Reset">
    </form>
    </body>
    </html>
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  7. The Following User Says Thank You to jscheuer1 For This Useful Post:

    Falkon303 (05-27-2011)

  8. #7
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Talking

    Quote Originally Posted by jscheuer1 View Post
    This ended up intriguing me. Here's something you may or may not find useful:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>Scientific Notation to String Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">
    
    function exp2string(num){
    	num = num - 0;
    	var numStr = num.toString(10), re = exp2string.re;
    	if(!re[0].test(numStr) || typeof num !== 'number' || isNaN(num)){
    		alert((typeof num !== 'number' || isNaN(num)? 'exp2string requires a number as input' : 'exp2string requires a number in scientific notation') +
    		'. Returning ' + (isNaN(num)? 'NaN (Not a Number)' : 'Input') + '.');
    		return num;
    	}
    	var numAr = num.toString(10).split(re[3]), result;
    	numAr[0] = numAr[0].replace(re[1], '');
    	if(re[2].test(numAr[1])){
    		result = '0.';
    		numAr[1] = numAr[1] * -1 - 2;
    		for (var i = numAr[1]; i > -1; --i){
    			result += '0';
    		}
    		result += numAr[0];
    	} else {
    		result = numAr[0];
    		numAr[1] = numAr[1] - numAr[0].length;
    		for (var i = numAr[1]; i > -1; --i){
    			result += '0';
    		}
    	}
    		return result;
    }
    exp2string.re = [/^\d\.\d+e[-+]\d+$/i, /\./, /-/, /e/i];
    
    </script>
    <style type="text/css">
    body {
    	color: #000;
    	background-color: #fff;
    	font: normal 85% verdana, arial, sans-serif;
    }
    #strNote {
    	vertical-align: top;
    }
    </style>
    </head>
    <body>
    <form action="#" onsubmit="return false;">
    Input Scientific Notation (#.#e+/-#): <input size=30 id="sciNote" type="text" value="3.6778967343747667e-196"><br>
    <script type="text/javascript">
    /* <![CDATA[ */
    document.write('Result: <textarea id="strNote" cols="50" rows="1" wrap="off" readonly><\/textarea><br>');
    /* ]]> */
    </script>
    <input type="button" value="Go" onclick="document.getElementById('strNote').value = exp2string(document.getElementById('sciNote').value);"><br>
    <input type="button" value="Check Equality" onclick="alert(document.getElementById('strNote').value - 0 == document.getElementById('sciNote').value - 0);"><br>
    <input type="reset" value="Reset">
    </form>
    </body>
    </html>

    That's very useful Jscheuer, unfortunately 3.6778967343747667e+19678 returns infinity.

    There is actually an app that gets very close to what I am trying to do for ubuntu called genius calculator - http://www.jirka.org/genius.html#download

    If you have an ubuntu on virtualbox, this is worth trying out, as it very easily did 40+ digits divisions.

    I am looking for something that will do much larger length numbers, but I've emailed the author asking him for some help. We'll see.

    Thanks for the help!
    document.write is document.wrong

  9. #8
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Cool

    Found this online, and it looks like something interesting that may work for dividing large numbers

    1) check divisior < dividend, otherwise it's zero (because it will be an int division)
    2) start from the left
    3) get equal portion of digits from the dividend
    4) if it's divisor portion is still bigger, increment digits of dividend portion by 1
    5) multiply divisor by 1-9 through the loop
    6) when it exceeds the dividend portion, previous multiplier is the answer
    7) repeat steps 3 to 5 until reaching to the end

    I am a bit foggy as to how to actually program this, or how it works, but apparently it's a c++ method for dividing large numbers. Taken from http://stackoverflow.com/questions/2...-large-numbers

    I am curious if it could be recreated for javascript, or better yet if someone can simplify how the heck this works. I am thinking that this is what jscheuer1 created probably.

    There is a program that divides exactly the way I am attempting to here - http://www.webmath.com/cgi-bin/divid...D4156145615618
    This way you aren't limited by the length of the number.
    Last edited by Falkon303; 05-29-2011 at 08:02 PM.
    document.write is document.wrong

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •