I am using a function where large integers are passed as a parameter.
For example.
doSomethingWithInteger(1234567890)
However, it's a little difficult to keep track of the place value of integer (and thus its value), if I do something like this:
doSomethingWithInteger(101934109348)
How many digits, and thus what is the actual value of that integer really? It's hard to keep track. Obviously the following example blows up with an error because it's interpreted as multiple arguments:
doSomethingWithInteger(101 934 109 348)
But is there a way to achieve some effect like that in JS to make the amount of digits, and thus the value of the integer more clear?
Edit: To clarify, I'm having trouble keeping track of the value of the numbers by not being able to track the place values, and not having trouble determining the length of the string.
There's no solution built in to the syntax but I suppose you could do something this with a function.
function toInt(arr) {
return parseInt(arr.join(''));
}
toInt([123, 456, 7890]); // 1234567890
doSomethingWithInteger(toInt([101, 934, 109, 348]));
This works by taking in an array, combining the entire array into a single string, then casting that string to an integer. Obviously you'll incur a performance hit with this.
Do you want to know the number of digits that has the int?
You can get it by doing this:
(12324897928).toString().length
Related
(newbie here)
i have large floating-point arrays created by node.js that i need to pass to s client-side jquery-ajax function. the goal is download it the fastest way possible.
we can safely round off the floating-point to the hundredth position, maybe even the tenth position - but i still need to experiment to see which one works best.
so far i have multiplied each array value by 100 and rounded off to just have three digits:
wholeNbrValue = Math.round(floatingPointValue * Math.pow(10, 3));
so for example 0.123456 would become 123. then each set of digits is appended to a string:
returnString += sprintfJs('%03d', wholeNbrValue) ;
i end up with a rather long ascii string of digits. then i might use something like fs.createWriteStream to store the string on the server as an ordinary file, and later use jquery-ajax to fetch it on the client side.
my question: what might be the optimum way to store a numeric only string? i am tempted to loop back through the string again and use something like charCodeAt() and just grab up every two positions as an ascii value, or even grab every 64 digits and convert it to a four-byte hex value.
or perhaps is there some way using node to actually store a binary floating-point array and later retrieve it with jquery-ajax?
thank you very much.
I'm writing a javascript program that needs random 10-digit numbers which can sometimes have the 10th digit as 0. I assigned a variable to one of these numbers and then logged it to make sure everything was alright...but it wasn't. Here is my code:
var candidate = 0135740250;
var candidate2 = 0272189318;
console.log(candidate); // Returns 24625320
console.log(candidate2); // Returns 272189318
I tried taking the 0 off the beginning of candidate, and that made it return correctly, but I don't understand why it doesn't work in the first place. I included candidate2 above because whatever I do to it, adding 0s in the middle, changing it in other ways, it stays correct, so I can't figure out why candidate is being screwed up. I vaguely understand the number storage system in Javascript and that its not perfect, but I need a predictable, repeatable way to return the correct number.
The question is: what is happening here and how can I reliably avoid it?
"The question is: what is happening here..."
The first is a valid octal, so it gets converted as such.
The second is not a valid octal because of the 8 and 9, so it gets the base 10 representation with the leading 0 removed since it adds no value.
"...and how can I reliably avoid it?"
Avoiding it will depend on how you're generating your numbers. If you were using .random() it wouldn't be an issue, so I'd assume they're coming from some sort of string representation.
If so, and if you're using parseInt() to get the actual number, then pass it 10 as the second argument to ensure base-10 representation.
JavaScript treats any number beginning with 0 as octal if it is a valid octal.
Another quack is, if you know the length of string to generate
"use strict"
var strlent = 10
console.log(candidate2.toString().length < strlent ? "0" +
candidate2.toString() : candidate2.toString())
>>>0272189318
Given I have an array like this:
array = [Array[8], Array[8], Array[8], ...]
# array.length is 81; each octet represents a point on a 9x9 grid
where each nested array contains 8 numeric elements ranging from -2 to 2, how would I apply the following step to get a vector in Javascript?
Step 5. The signature of an image is simply the concatenation of the
8-element arrays corresponding to the grid points, ordered
left-to-right, top-to-bottom. Our signatures are thus vectors of
length 648. We store them in 648-byte arrays, but because some of the
entries for the first and last rows and columns are known to be zeros
and because each byte is used to hold only 5 values, signatures could
be represented by as few as ⌈544 log2 5⌉ = 1264
bits.
(Towards the end, those are supposed to be ceiling notations; best I could do given SO's lack of Latex formatting)
I have the array ready to go and ordered properly, but my knowledge of matricies and vectors is a little rusty, so I'm not sure how to tackle this next step. I'd appreciate any clarifications!
Background: I'm trying to create a JS implementation of an image processing algorithm published by the Xerox Palo Alto Research Center for a side-project I'm currently working on.
Conceptually you could convert this to a single 1264 bit number using the following algorithm:
Initialize an accumulator variable to zero
Iterate over all elements, but skipt those which you know to be zero
For the other elements, add 2 to obtain values in the range [0,1,2,3,4]
For each such value, multiply the accumulator by 5 then add the corresponding value
When you have processed all elements, the accumulator will encode your arrays
To reverse that encoding, youd do this:
Read the encoded value into the accumulator
Iterate over all elements, in reverse order, but skipt those which you know to be zero
For each element, you obtain the corresponding value as the accumulator modulo 5
Subtract 2 from that value
Divide the accumulator by 5 using a truncating division
The problem with all of this is the fact that JS doesn't provide 1264 bit numbers out of the box. You might try one of the libraries suggested in How to deal with big numbers in javascript.
But unless you absolutely requre an extremely small representation, I'd suggest an alternative approach: you can encode up to 13 such values in a 32 bit signed integer, since 513=1,220,703,125 < 2,147,483,648=231. So after encoding 13 values I'd write out the result using such a number, then reset the accumulator to zero. This way you'll need ⌈544/13⌉∙32=1376 bits, which is not that much worse in terms of space requirements, but will be a lot faster to implement.
Instead of iterating once in forward and once in reverse direction, it might be easier to not multiply the accumulator by 5, but instead multiply the value you add to that by a suitable power of 5. In other words, you maintain a factor which you initialize to 1, and multiply by 5 every time you add a value. So in this case, first data values will have less significant positions than later data values, both for encoding and decoding, which means you can use the same iteration order for both.
See the ideone link mentioned in my comment below for an example of this latter approach. It encodes the full 9*9*8 values in 50 integers, each of them using no more than 31 bits. It then decodes the original matrix from that encoded form, to show that all the information is still present. The example does not use any fixed zeros, in your case ⌈544/13⌉=42 integers should be enough.
I was wondering why do people have to convert numbers to string. What are the practical uses for that kind of conversion?
Similarly why do developers use parseInt or parseFloat to convert a string to a number.
thanks
The variable’s data type is the JavaScript scripting engine’s interpretation of the type of data that variable is currently holding. A string variable holds a string; a number variable holds a number value, and so on. However, unlike many other languages, in JavaScript, the same variable can hold different types of data, all within the same application. This is a concept known by the terms loose typing and dynamic typing, both of which mean that a JavaScript variable can hold different data types at different times depending on context.
With a loosely typed language, you don’t have to declare ahead of time that a variable will be a string or a number or a boolean, as the data type is actually determined while the application is being processed. If you start out with a string variable and then want to use it as a number, that’s perfectly fine, as long as the string actually contains something that resembles a number and not something such as an email address. If you later want to treat it as a string again, that’s fine, too.
The forgiving nature of loose typing can end up generating problems. If you try to add two numbers together, but the JavaScript engine interprets the variable holding one of them as a string data type, you end up with an odd string, rather than the sum you were expecting. Context is everything when it comes to variables and data types with JavaScript.
Using parseInt and parseFloat is important if you want to do arithmetic operations on a number which is in string form. For example
"42" + 1 === "421"
parseInt("42") + 1 === 43;
The reverse is true when you want to do string operations on values which are currently a number.
42 + 1 === 43
(42 + "") + 1 === 421
Why one would want to do the former or latter though is very scenario specific. I'd wager the case of converting strings to numbers for arithmetic operations is the more prominent case though.
An example of when converting numbers to strings is useful is when you want to format the number a certain way, perhaps like a currency (1234.56 -> $1,234.56).
The converse is useful when you want to do arithmetic on strings the represent numbers. Say you have a text box were you allow the user to input a number. The value of that text box will be a string, but you need it as a number to do some arithmetic with it, so you would use parseInt and parseFloat.
string -> number:
Think about simple number validation using JS. if you can convert a string into a number, then you can validate that number before posting to a number, or for use in an arithmetic operation.
number -> string:
String concatenation mainly and display purposes. The language will most often use implicit conversion to convert the number into a string anyway, such as:
1 + " new answer has been posted"
Do remember, Javascript is a loosely typed language. This can hide a lot of implicit type-casting that is occurring.
I have an interesting question, I have been doing some work with javascript and a database ID came out as "3494793310847464221", now this is being entered into javascript as a number yet it is using the number as a different value, both when output to an alert and when being passed to another javascript function.
Here is some example code to show the error to its fullest.
<html><head><script language="javascript">alert( 3494793310847464221);
var rar = 3494793310847464221;
alert(rar);
</script></head></html>
This has completly baffeled me and for once google is not my friend...
btw the number is 179 more then the number there...
Your number is larger than the maximum allowed integer value in javascript (2^53). This has previously been covered by What is JavaScript's highest integer value that a Number can go to without losing precision?
In JavaScript, all numbers (even integral ones) are stored as IEEE-754 floating-point numbers. However, FPs have limited "precision" (see the Wikipedia article for more info), so your number isn't able to be represented exactly.
You will need to either store your number as a string or use some other "bignum" approach (unfortunately, I don't know of any JS bignum libraries off the top of my head).
Edit: After doing a little digging, it doesn't seem as if there's been a lot of work done in the way of JavaScript bignum libraries. In fact, the only bignum implementation of any kind that I was able to find is Edward Martin's JavaScript High Precision Calculator.
Use a string instead.
179 more is one way to look at it. Another way is, after the first 16 digits, any further digit is 0. I don't know the details, but it looks like your variable only stores up to 16 digits.
That number exceeds (2^31)-1, and that's the problem; javascript uses 32-bit signed integers (meaning, a range from –2,147,483,648 to 2,147,483,647). Your best choice is to use strings, and create functions to manipulate the strings as numbers.
I wouldn't be all too surprised, if there already was a library that does what you need.
One possible solution is to use a BigInt library such as: http://www.leemon.com/crypto/BigInt.html
This will allow you to store integers of arbitrary precision, but it will not be as fast as standard arithmetic.
Since it's to big to be stored as int, it's converted to float. In JavaScript ther is no explicit integer and float types, there's only universal Number type.
"Can't increment and decrement a string easily..."
Really?
function incr_num(x) {
var lastdigit=Number(x.charAt(x.length-1));
if (lastdigit!=9) return (x.substring(0,x.length-1))+""+(lastdigit+1);
if (x=="9") return "10";
return incr_num(x.substring(0,x.length-1))+"0";
}
function decr_num(x) {
if(x=="0") return "(error: cannot decrement zero)";
var lastdigit=Number(x.charAt(x.length-1));
if (lastdigit!=0) return (x.substring(0,x.length-1))+""+(lastdigit-1);
if (x=="10") return "9"; // delete this line if you like leading zero
return decr_num(x.substring(0,x.length-1))+"9";
}
Just guessing, but perhaps the number is stored as a floating type, and the difference might be because of some rounding error. If that is the case it might work correctly if you use another interpreter (browser, or whatever you are running it in)