I want a concise expression to tell me if a given value is an integer or float. When provided the input value NaN or Infinity, I want the output value to be false, so this rules out simply checking whether typeof(val) == 'number'  Desired input / output:   1 => true -42 => true 3.14 => true NaN => false Infinity => false null => false undefined => false   isFinite() is almost perfect, but there's one gotcha: isFinite(null) returns true, when I actually want it to return false.  Short of always checking if ((val != nul) &amp;&amp; isFinite(val)), is there another more concise technique?
2827
What's the cleanest, most effective way to validate decimal numbers in JavaScript?  Bonus points for:   Clarity. Solution should be clean and simple. Cross-platform.   Test cases:  01. IsNumeric('-1')      =&gt; true 02. IsNumeric('-1.5')    =&gt; true 03. IsNumeric('0')       =&gt; true 04. IsNumeric('0.42')    =&gt; true 05. IsNumeric('.42')     =&gt; true 06. IsNumeric('99,999')  =&gt; false 07. IsNumeric('0x89f')   =&gt; false 08. IsNumeric('#abcdef') =&gt; false 09. IsNumeric('1.2.3')   =&gt; false 10. IsNumeric('')        =&gt; false 11. IsNumeric('blah')    =&gt; false
80880
My code:  a = '2.3'   I wanted to display a as a floating point value.  Since a is a string, I tried:  float(a)   The result I got was :  2.2999999999999998   I want a solution for this problem. Please, kindly help me.  I was following .
2846
Why does the following behave unexpectedly in Python?  &gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; a is b True           # This is an expected result &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; a is b False          # What happened here? Why is this False? &gt;&gt;&gt; 257 is 257 True           # Yet the literal numbers compare properly   I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.  Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the is operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?
121122
I was implementing the ALU from the specs given in my The Elements of Computing systems book. I am stuck on only one problem. How do I find if a given number is zero or not. One thing I can do is or every bit in the bus, and then apply a not gate on that. But there has to be some other elegant solution.
58651
Does anybody know if there is a way to evaluate a string containing boolean-logic at runtime? My logic, can only contain three operators and parenthesis (AND, OR, NOT). I can even make the string look like this: true &amp;&amp; false &amp;&amp; (true || !true)  I don't have the bandwidth to build a full-on parser... Any ideas?  PS: I saw some answers that pointed to the use of an API but I don't have access to use the Toolkit API in the environment this will get deployed.
3996
I'm looking for the fastest way to determine if a long value is a perfect square (i.e. its square root is another integer):    I've done it the easy way, by using the built-in  function, but I'm wondering if there is a way to do it faster by restricting yourself to integer-only domain. Maintaining a lookup table is impractical (since there are about 231.5 integers whose square is less than 263).   Here is the very simple and straightforward way I'm doing it now:  public final static boolean isPerfectSquare(long n) {   if (n &lt; 0)     return false;    long tst = (long)(Math.sqrt(n) + 0.5);   return tst*tst == n; }   Note: I'm using this function in many  problems.  So no one else will ever have to maintain this code.  And this kind of micro-optimization could actually make a difference, since part of the challenge is to do every algorithm in less than a minute, and this function will need to be called millions of times in some problems.    I've tried the different solutions to the problem:   After exhaustive testing, I found that adding 0.5 to the result of Math.sqrt() is not necessary, at least not on my machine. The  was faster, but it gave incorrect results for n >= 410881.  However, as suggested by , we can use the FISR hack for n &lt; 410881. Newton's method was a good bit slower than Math.sqrt().  This is probably because Math.sqrt() uses something similar to Newton's Method, but implemented in the hardware so it's much faster than in Java.  Also, Newton's Method still required use of doubles. A modified Newton's method, which used a few tricks so that only integer math was involved, required some hacks to avoid overflow (I want this function to work with all positive 64-bit signed integers), and it was still slower than Math.sqrt(). Binary chop was even slower.  This makes sense because the binary chop will on average require 16 passes to find the square root of a 64-bit number. According to John's tests, using or statements is faster in C++ than using a switch, but in Java and C# there appears to be no difference between or and switch. I also tried making a lookup table (as a private static array of 64 boolean values).  Then instead of either switch or or statement, I would just say if(lookup[(int)(n&amp;0x3F)]) { test } else return false;.  To my surprise, this was (just slightly) slower. This is because .
41167
I am told that good developers can spot/utilize the difference between Null and False and 0 and all the other good "nothing" entities. What is the difference, specifically in PHP?  Does it have something to do with ===?
23208
I have been asked to test a library provided by a 3rd party. The library is known to be accurate to n significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:  def nearlyequal( a, b, sigfig=5 ):   The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to sigfig significant-figures when written in decimal.   Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:  assert nearlyequal(1, 1, 5)  assert nearlyequal(1.0, 1.0, 5)  assert nearlyequal(1.0, 1.0, 5)  assert nearlyequal(-1e-9, 1e-9, 5)  assert nearlyequal(1e9, 1e9 + 1 , 5)  assert not nearlyequal( 1e4, 1e4 + 1, 5)  assert nearlyequal( 0.0, 1e-15, 5 )  assert not nearlyequal( 0.0, 1e-4, 6 )    Additional notes:   Values a and b might be of type int, float or numpy.float64. Values a and b will always be of the same type. It's vital that conversion does not introduce additional error into the function. Lets keep this numerical, so functions that convert to strings or use non-mathematical tricks are not ideal. This program will be audited by somebody who is a mathematician who will want to be able to prove that the function does what it is supposed to do. Speed... I've got to compare a lot of numbers so the faster the better. I've got numpy, scipy and the standard-library. Anything else will be hard for me to get, especially for such a small part of the project.
60449
I see that within MySQL there are Cast() and Convert() functions to create integers from values, but is there any way to check to see if a value is an integer?  Something like is_int() in PHP is what I am looking for.
25615
Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript?  I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.  The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.  var myValue = document.myForm.IS_TRUE.value; var isTrueSet = myValue == 'true';   Is there a better way to accomplish this?
117193
Do we need to be careful when comparing a double value against zero?  if ( someAmount &lt;= 0){ ..... }
56396
I am aware that 1/0 is undefined for two reasons:   If you would have to give an answer to this it is infinity which is not a number but a concept; The limit of 1/x for $x \to 0$ is either positive or negative infinity and since it has two limits we cannot state what its exact value is   How can we use this for square roots? It has multiple answers so why do we pick the positive one? if $x^2 = 16 \implies x = \sqrt{16} $ or $x = -\sqrt{16}$ for respectively the positive and negative solution. This implies that the square root function has a single answer and we must negate its answer to obtain the second solution. I understand this is extremely practical but it feels like 'cheating' since we know that there are 2 solutions, but in the function we simply ignore one of them. Is this correct?
9601
I want to take a floating point number in C++, like 2.25125, and a int array filled with the binary value that is used to store the float in memory (IEEE 754).  So I could take a number, and end up with a int num[16] array with the binary value of the float: num[0] would be 1 num[1] would be 1 num[2] would be 0 num[3] would be 1 and so on...  Putting an int into an array isn't difficult, just the process of getting the binary value of a float is where I'm stuck. Can you just read the binary in the memory that the float variable? If not, how could I go about doing this in C++?  EDIT: The reason for doing the comparison this way is that I am wanting to learn to do bitwise operations in C++.
52629
Is there any way I can specify a standard or custom numeric format string to always output the sign, be it +ve or -ve (although what it should do for zero, I'm not sure!)
120706
I want to do the following: I am generating a report which can be set to be in imperial or metric units. All values are originally in metric units, so in the case of imperial units all values should be converted. Some values can be say N/A or any other string value, in case the value is not applicable. The document is automatically generated. For conversion I am using the fp package, but the challenge is the checking the input. The fp package (and pgfmath) will ofcourse) err if you try to do math with non-numerical values. This is what I currently have (only works for integer input)  % Convert meters to inches \newcommand{\convertmtoin}[2] {     \if!\ifnum9&lt;1#1!\else_\fi        \FPeval{val}{#1*39.3700787} \FPround{\val}{\val}{#2}     \else     \def\val{#1}     \fi }   Using pgfmath one could do something like this  \newcommand{\convertmtoin}[2] {     \pgfmathfloatparsenumber{#1}     \pgfmathfloatifflags{\pgfmathresult}{3}{\FPeval{val}{#1*39.3700787} \FPround{\val}{\val}{#2}}{\def\val{#1}}  }   But I am not able to set the error handler of pgfmath to output NaN in the case of erronous input to pgfmathfloatparsenumber  \pgfkeys{/pgf/fpu/handlers/invalid number={??}{??}}   Thanks for any help!
2266
In follow up to , it appears that some numbers cannot be represented by floating point at all, and instead are approximated.  How are floating point numbers stored?  Is there a common standard for the different sizes?  What kind of gotchas do I need to watch out for if I use floating point?  Are they cross-language compatible (ie, what conversions do I need to deal with to send a floating point number from a python program to a C program over TCP/IP)?
42817
Possible Duplicate:          What's a way to see if a number is a ?   bool IsPerfectSquare(long input) {    // TODO }   I'm using C# but this is language agnostic.  Bonus points for clarity and simplicity (this isn't meant to be code-golf).    Edit: This got much more complex than I expected! It turns out the problems with double precision manifest themselves a couple ways. First, Math.Sqrt takes a double which can't precisely hold a long (thanks Jon).   Second, a double's precision will lose small values ( .000...00001) when you have a huge, near perfect square. e.g., my implementation failed this test for Math.Pow(10,18)+1 (mine reported true).