Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get sign of a number?

Tags:

php

math

sign

Is there a (simple) way to get the "sign" of a number (integer) in PHP comparable to gmp_signDocs:

  • -1 negative
  • 0 zero
  • 1 positive

I remember there is some sort of compare function that can do this but I'm not able to find it at the moment.

I quickly compiled this (Demo) which does the job, but maybe there is something more nifty (like a single function call?), I would like to map the result onto an array:

$numbers = array(-100, 0, 100);  foreach($numbers as $number) {    echo $number, ': ', $number ? abs($number) / $number : 0, "\n"; } 

(this code might run into floating point precision problems probably)

Related: Request #19621 Math needs a "sign()" function

like image 774
hakre Avatar asked Sep 26 '11 14:09

hakre


People also ask

How do I get the sign of a number in R?

Get the Sign of Elements of a Numeric Vector in R Programming – sign() Function. sign() function in R Language is used to find the sign of the elements of the numeric vector provided as argument.

What is sign () in Python?

sign() in Python. numpy. sign(array [, out]) function is used to indicate the sign of a number element-wise. For integer inputs, if array value is greater than 0 it returns 1, if array value is less than 0 it returns -1, and if array value 0 it returns 0.

Is 0 A sign number?

Signed zero is zero with an associated sign. In ordinary arithmetic, the number 0 does not have a sign, so that −0, +0 and 0 are identical.


2 Answers

Here's a cool one-liner that will do it for you efficiently and reliably:

function sign($n) {     return ($n > 0) - ($n < 0); } 
like image 64
Milosz Avatar answered Sep 28 '22 10:09

Milosz


In PHP 7 you should use the combined comparison operator (<=>):

$sign = $i <=> 0; 
like image 37
kdojeteri Avatar answered Sep 28 '22 08:09

kdojeteri