Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

265
Views
¿Por qué double.IsNegative(double.NaN) devuelve verdadero?

¿Por qué double.IsNegative(double.NaN) inesperadamente devuelve true mientras que double.NaN < 0 devuelve false como se esperaba?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

El IEEE754 define números de coma flotante. El bit más alto se usa para definir el signo, siendo 0 positivo y 1 negativo.

A través de un poco de excavación, double.NaN parece estar representado como 0xFFF8000000000000 en binario (y 0.0 / 0.0 en código de alguna manera).

double.IsNegative(double d) solo verifica el bit más alto sin involucrar ninguna matemática real. Por lo tanto, NaN se interpreta como un valor negativo. Mientras tanto, double.NaN , si se usa en una comparación binaria, siempre arrojará falso:

 double.NaN < 0.0 //false double.NaN > 0.0 //false double.NaN <= 0.0 //false double.NaN >= 0.0 //false double.NaN == 0.0 //false
over 4 years ago · Santiago Trujillo Report

0

Bueno, según la fuente de referencia, double.IsNegative solo verifica el bit más significativo :

 [Pure] [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static bool IsNegative(double d) { return (*(UInt64*)(&d) & 0x8000000000000000) == 0x8000000000000000; }

En el caso de double.NaN , se establece el bit más significativo:

 11111111 11111000 00000000 00000000 00000000 00000000 00000000 00000000 || || | |<- Exp -><- Mantissa -> Sign

Es por eso que double.IsNegative devuelve true

Cuando ponemos < o > se utilizan comandos FPU que saben que todos los exponentes son un tipo especial de valor de coma flotante que debe tratarse de una manera especial.

La misma imagen es con Single.NaN .

Tenga en cuenta que podemos construir otro valor extraño, cero negativo :

 10000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 || || | |<- Exp -><- Mantissa -> Sign

Por favor mira:

 double negativeZero = BitConverter.ToDouble(new byte[] { 0, 0, 0, 0, 0, 0, 0, 128 }); Console.WriteLine(negativeZero == 0 ? "Zero" : "???"); Console.WriteLine(double.IsNegative(negativeZero) ? "Negative" : "???");
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!