Single Estrutura

Definição

Representa um número de ponto flutuante de precisão simples.

public value class float : IComparable, IComparable<float>, IConvertible, IEquatable<float>, IFormattable
public value class float : IComparable, IComparable<float>, IConvertible, IEquatable<float>, ISpanFormattable
public value class float : IComparable<float>, IConvertible, IEquatable<float>, IParsable<float>, ISpanParsable<float>, System::Numerics::IAdditionOperators<float, float, float>, System::Numerics::IAdditiveIdentity<float, float>, System::Numerics::IBinaryFloatingPointIeee754<float>, System::Numerics::IBinaryNumber<float>, System::Numerics::IBitwiseOperators<float, float, float>, System::Numerics::IComparisonOperators<float, float, bool>, System::Numerics::IDecrementOperators<float>, System::Numerics::IDivisionOperators<float, float, float>, System::Numerics::IEqualityOperators<float, float, bool>, System::Numerics::IExponentialFunctions<float>, System::Numerics::IFloatingPoint<float>, System::Numerics::IFloatingPointConstants<float>, System::Numerics::IFloatingPointIeee754<float>, System::Numerics::IHyperbolicFunctions<float>, System::Numerics::IIncrementOperators<float>, System::Numerics::ILogarithmicFunctions<float>, System::Numerics::IMinMaxValue<float>, System::Numerics::IModulusOperators<float, float, float>, System::Numerics::IMultiplicativeIdentity<float, float>, System::Numerics::IMultiplyOperators<float, float, float>, System::Numerics::INumber<float>, System::Numerics::INumberBase<float>, System::Numerics::IPowerFunctions<float>, System::Numerics::IRootFunctions<float>, System::Numerics::ISignedNumber<float>, System::Numerics::ISubtractionOperators<float, float, float>, System::Numerics::ITrigonometricFunctions<float>, System::Numerics::IUnaryNegationOperators<float, float>, System::Numerics::IUnaryPlusOperators<float, float>
public value class float : IComparable<float>, IConvertible, IEquatable<float>, IParsable<float>, ISpanParsable<float>, IUtf8SpanParsable<float>, System::Numerics::IAdditionOperators<float, float, float>, System::Numerics::IAdditiveIdentity<float, float>, System::Numerics::IBinaryFloatingPointIeee754<float>, System::Numerics::IBinaryNumber<float>, System::Numerics::IBitwiseOperators<float, float, float>, System::Numerics::IComparisonOperators<float, float, bool>, System::Numerics::IDecrementOperators<float>, System::Numerics::IDivisionOperators<float, float, float>, System::Numerics::IEqualityOperators<float, float, bool>, System::Numerics::IExponentialFunctions<float>, System::Numerics::IFloatingPoint<float>, System::Numerics::IFloatingPointConstants<float>, System::Numerics::IFloatingPointIeee754<float>, System::Numerics::IHyperbolicFunctions<float>, System::Numerics::IIncrementOperators<float>, System::Numerics::ILogarithmicFunctions<float>, System::Numerics::IMinMaxValue<float>, System::Numerics::IModulusOperators<float, float, float>, System::Numerics::IMultiplicativeIdentity<float, float>, System::Numerics::IMultiplyOperators<float, float, float>, System::Numerics::INumber<float>, System::Numerics::INumberBase<float>, System::Numerics::IPowerFunctions<float>, System::Numerics::IRootFunctions<float>, System::Numerics::ISignedNumber<float>, System::Numerics::ISubtractionOperators<float, float, float>, System::Numerics::ITrigonometricFunctions<float>, System::Numerics::IUnaryNegationOperators<float, float>, System::Numerics::IUnaryPlusOperators<float, float>
public value class float : IComparable, IConvertible, IFormattable
public value class float : IComparable, IComparable<float>, IEquatable<float>, IFormattable
public struct Single : IComparable, IComparable<float>, IConvertible, IEquatable<float>, IFormattable
public readonly struct Single : IComparable, IComparable<float>, IConvertible, IEquatable<float>, IFormattable
public readonly struct Single : IComparable, IComparable<float>, IConvertible, IEquatable<float>, ISpanFormattable
public readonly struct Single : IComparable<float>, IConvertible, IEquatable<float>, IParsable<float>, ISpanParsable<float>, System.Numerics.IAdditionOperators<float,float,float>, System.Numerics.IAdditiveIdentity<float,float>, System.Numerics.IBinaryFloatingPointIeee754<float>, System.Numerics.IBinaryNumber<float>, System.Numerics.IBitwiseOperators<float,float,float>, System.Numerics.IComparisonOperators<float,float,bool>, System.Numerics.IDecrementOperators<float>, System.Numerics.IDivisionOperators<float,float,float>, System.Numerics.IEqualityOperators<float,float,bool>, System.Numerics.IExponentialFunctions<float>, System.Numerics.IFloatingPoint<float>, System.Numerics.IFloatingPointConstants<float>, System.Numerics.IFloatingPointIeee754<float>, System.Numerics.IHyperbolicFunctions<float>, System.Numerics.IIncrementOperators<float>, System.Numerics.ILogarithmicFunctions<float>, System.Numerics.IMinMaxValue<float>, System.Numerics.IModulusOperators<float,float,float>, System.Numerics.IMultiplicativeIdentity<float,float>, System.Numerics.IMultiplyOperators<float,float,float>, System.Numerics.INumber<float>, System.Numerics.INumberBase<float>, System.Numerics.IPowerFunctions<float>, System.Numerics.IRootFunctions<float>, System.Numerics.ISignedNumber<float>, System.Numerics.ISubtractionOperators<float,float,float>, System.Numerics.ITrigonometricFunctions<float>, System.Numerics.IUnaryNegationOperators<float,float>, System.Numerics.IUnaryPlusOperators<float,float>
public readonly struct Single : IComparable<float>, IConvertible, IEquatable<float>, IParsable<float>, ISpanParsable<float>, IUtf8SpanParsable<float>, System.Numerics.IAdditionOperators<float,float,float>, System.Numerics.IAdditiveIdentity<float,float>, System.Numerics.IBinaryFloatingPointIeee754<float>, System.Numerics.IBinaryNumber<float>, System.Numerics.IBitwiseOperators<float,float,float>, System.Numerics.IComparisonOperators<float,float,bool>, System.Numerics.IDecrementOperators<float>, System.Numerics.IDivisionOperators<float,float,float>, System.Numerics.IEqualityOperators<float,float,bool>, System.Numerics.IExponentialFunctions<float>, System.Numerics.IFloatingPoint<float>, System.Numerics.IFloatingPointConstants<float>, System.Numerics.IFloatingPointIeee754<float>, System.Numerics.IHyperbolicFunctions<float>, System.Numerics.IIncrementOperators<float>, System.Numerics.ILogarithmicFunctions<float>, System.Numerics.IMinMaxValue<float>, System.Numerics.IModulusOperators<float,float,float>, System.Numerics.IMultiplicativeIdentity<float,float>, System.Numerics.IMultiplyOperators<float,float,float>, System.Numerics.INumber<float>, System.Numerics.INumberBase<float>, System.Numerics.IPowerFunctions<float>, System.Numerics.IRootFunctions<float>, System.Numerics.ISignedNumber<float>, System.Numerics.ISubtractionOperators<float,float,float>, System.Numerics.ITrigonometricFunctions<float>, System.Numerics.IUnaryNegationOperators<float,float>, System.Numerics.IUnaryPlusOperators<float,float>
[System.Serializable]
public struct Single : IComparable, IConvertible, IFormattable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public struct Single : IComparable, IComparable<float>, IConvertible, IEquatable<float>, IFormattable
public struct Single : IComparable, IComparable<float>, IEquatable<float>, IFormattable
type single = struct
    interface IConvertible
    interface IFormattable
type single = struct
    interface IConvertible
    interface ISpanFormattable
    interface IFormattable
type single = struct
    interface IConvertible
    interface IFormattable
    interface IParsable<single>
    interface ISpanFormattable
    interface ISpanParsable<single>
    interface IAdditionOperators<single, single, single>
    interface IAdditiveIdentity<single, single>
    interface IBinaryFloatingPointIeee754<single>
    interface IBinaryNumber<single>
    interface IBitwiseOperators<single, single, single>
    interface IComparisonOperators<single, single, bool>
    interface IEqualityOperators<single, single, bool>
    interface IDecrementOperators<single>
    interface IDivisionOperators<single, single, single>
    interface IIncrementOperators<single>
    interface IModulusOperators<single, single, single>
    interface IMultiplicativeIdentity<single, single>
    interface IMultiplyOperators<single, single, single>
    interface INumber<single>
    interface INumberBase<single>
    interface ISubtractionOperators<single, single, single>
    interface IUnaryNegationOperators<single, single>
    interface IUnaryPlusOperators<single, single>
    interface IExponentialFunctions<single>
    interface IFloatingPointConstants<single>
    interface IFloatingPoint<single>
    interface ISignedNumber<single>
    interface IFloatingPointIeee754<single>
    interface IHyperbolicFunctions<single>
    interface ILogarithmicFunctions<single>
    interface IPowerFunctions<single>
    interface IRootFunctions<single>
    interface ITrigonometricFunctions<single>
    interface IMinMaxValue<single>
type single = struct
    interface IConvertible
    interface IFormattable
    interface IParsable<single>
    interface ISpanFormattable
    interface ISpanParsable<single>
    interface IAdditionOperators<single, single, single>
    interface IAdditiveIdentity<single, single>
    interface IBinaryFloatingPointIeee754<single>
    interface IBinaryNumber<single>
    interface IBitwiseOperators<single, single, single>
    interface IComparisonOperators<single, single, bool>
    interface IEqualityOperators<single, single, bool>
    interface IDecrementOperators<single>
    interface IDivisionOperators<single, single, single>
    interface IIncrementOperators<single>
    interface IModulusOperators<single, single, single>
    interface IMultiplicativeIdentity<single, single>
    interface IMultiplyOperators<single, single, single>
    interface INumber<single>
    interface INumberBase<single>
    interface ISubtractionOperators<single, single, single>
    interface IUnaryNegationOperators<single, single>
    interface IUnaryPlusOperators<single, single>
    interface IUtf8SpanFormattable
    interface IUtf8SpanParsable<single>
    interface IExponentialFunctions<single>
    interface IFloatingPointConstants<single>
    interface IFloatingPoint<single>
    interface ISignedNumber<single>
    interface IFloatingPointIeee754<single>
    interface IHyperbolicFunctions<single>
    interface ILogarithmicFunctions<single>
    interface IPowerFunctions<single>
    interface IRootFunctions<single>
    interface ITrigonometricFunctions<single>
    interface IMinMaxValue<single>
[<System.Serializable>]
type single = struct
    interface IFormattable
    interface IConvertible
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type single = struct
    interface IFormattable
    interface IConvertible
type single = struct
    interface IFormattable
Public Structure Single
Implements IComparable, IComparable(Of Single), IConvertible, IEquatable(Of Single), IFormattable
Public Structure Single
Implements IComparable, IComparable(Of Single), IConvertible, IEquatable(Of Single), ISpanFormattable
Public Structure Single
Implements IAdditionOperators(Of Single, Single, Single), IAdditiveIdentity(Of Single, Single), IBinaryFloatingPointIeee754(Of Single), IBinaryNumber(Of Single), IBitwiseOperators(Of Single, Single, Single), IComparable(Of Single), IComparisonOperators(Of Single, Single, Boolean), IConvertible, IDecrementOperators(Of Single), IDivisionOperators(Of Single, Single, Single), IEqualityOperators(Of Single, Single, Boolean), IEquatable(Of Single), IExponentialFunctions(Of Single), IFloatingPoint(Of Single), IFloatingPointConstants(Of Single), IFloatingPointIeee754(Of Single), IHyperbolicFunctions(Of Single), IIncrementOperators(Of Single), ILogarithmicFunctions(Of Single), IMinMaxValue(Of Single), IModulusOperators(Of Single, Single, Single), IMultiplicativeIdentity(Of Single, Single), IMultiplyOperators(Of Single, Single, Single), INumber(Of Single), INumberBase(Of Single), IParsable(Of Single), IPowerFunctions(Of Single), IRootFunctions(Of Single), ISignedNumber(Of Single), ISpanParsable(Of Single), ISubtractionOperators(Of Single, Single, Single), ITrigonometricFunctions(Of Single), IUnaryNegationOperators(Of Single, Single), IUnaryPlusOperators(Of Single, Single)
Public Structure Single
Implements IAdditionOperators(Of Single, Single, Single), IAdditiveIdentity(Of Single, Single), IBinaryFloatingPointIeee754(Of Single), IBinaryNumber(Of Single), IBitwiseOperators(Of Single, Single, Single), IComparable(Of Single), IComparisonOperators(Of Single, Single, Boolean), IConvertible, IDecrementOperators(Of Single), IDivisionOperators(Of Single, Single, Single), IEqualityOperators(Of Single, Single, Boolean), IEquatable(Of Single), IExponentialFunctions(Of Single), IFloatingPoint(Of Single), IFloatingPointConstants(Of Single), IFloatingPointIeee754(Of Single), IHyperbolicFunctions(Of Single), IIncrementOperators(Of Single), ILogarithmicFunctions(Of Single), IMinMaxValue(Of Single), IModulusOperators(Of Single, Single, Single), IMultiplicativeIdentity(Of Single, Single), IMultiplyOperators(Of Single, Single, Single), INumber(Of Single), INumberBase(Of Single), IParsable(Of Single), IPowerFunctions(Of Single), IRootFunctions(Of Single), ISignedNumber(Of Single), ISpanParsable(Of Single), ISubtractionOperators(Of Single, Single, Single), ITrigonometricFunctions(Of Single), IUnaryNegationOperators(Of Single, Single), IUnaryPlusOperators(Of Single, Single), IUtf8SpanParsable(Of Single)
Public Structure Single
Implements IComparable, IConvertible, IFormattable
Public Structure Single
Implements IComparable, IComparable(Of Single), IEquatable(Of Single), IFormattable
Herança
Single
Atributos
Implementações
IComparable IComparable<Single> IConvertible IEquatable<Single> IFormattable ISpanFormattable IComparable<TSelf> IEquatable<TSelf> IParsable<Single> IParsable<TSelf> ISpanParsable<Single> ISpanParsable<TSelf> IAdditionOperators<Single,Single,Single> IAdditionOperators<TSelf,TSelf,TSelf> IAdditiveIdentity<Single,Single> IAdditiveIdentity<TSelf,TSelf> IBinaryFloatingPointIeee754<Single> IBinaryNumber<Single> IBinaryNumber<TSelf> IBitwiseOperators<Single,Single,Single> IBitwiseOperators<TSelf,TSelf,TSelf> IComparisonOperators<Single,Single,Boolean> IComparisonOperators<TSelf,TSelf,Boolean> IDecrementOperators<Single> IDecrementOperators<TSelf> IDivisionOperators<Single,Single,Single> IDivisionOperators<TSelf,TSelf,TSelf> IEqualityOperators<Single,Single,Boolean> IEqualityOperators<TSelf,TOther,TResult> IEqualityOperators<TSelf,TSelf,Boolean> IExponentialFunctions<Single> IExponentialFunctions<TSelf> IFloatingPoint<Single> IFloatingPoint<TSelf> IFloatingPointConstants<Single> IFloatingPointConstants<TSelf> IFloatingPointIeee754<Single> IFloatingPointIeee754<TSelf> IHyperbolicFunctions<Single> IHyperbolicFunctions<TSelf> IIncrementOperators<Single> IIncrementOperators<TSelf> ILogarithmicFunctions<Single> ILogarithmicFunctions<TSelf> IMinMaxValue<Single> IModulusOperators<Single,Single,Single> IModulusOperators<TSelf,TSelf,TSelf> IMultiplicativeIdentity<Single,Single> IMultiplicativeIdentity<TSelf,TSelf> IMultiplyOperators<Single,Single,Single> IMultiplyOperators<TSelf,TSelf,TSelf> INumber<Single> INumber<TSelf> INumberBase<Single> INumberBase<TSelf> IPowerFunctions<Single> IPowerFunctions<TSelf> IRootFunctions<Single> IRootFunctions<TSelf> ISignedNumber<Single> ISignedNumber<TSelf> ISubtractionOperators<Single,Single,Single> ISubtractionOperators<TSelf,TSelf,TSelf> ITrigonometricFunctions<Single> ITrigonometricFunctions<TSelf> IUnaryNegationOperators<Single,Single> IUnaryNegationOperators<TSelf,TSelf> IUnaryPlusOperators<Single,Single> IUnaryPlusOperators<TSelf,TSelf> IUtf8SpanFormattable IUtf8SpanParsable<Single> IUtf8SpanParsable<TSelf>

Comentários

O Single tipo de valor representa um número de precisão única de 32 bits com valores que variam de 3,402823e38 a positivo 3,402823e38, bem como zero positivo ou negativo, PositiveInfinity, NegativeInfinitye não um número (NaN). Destina-se a representar valores extremamente grandes (como distâncias entre planetas ou galáxias) ou extremamente pequenos (como a massa molecular de uma substância em quilogramas) e que muitas vezes são imprecisos (como a distância da Terra para outro sistema solar). O Single tipo está em conformidade com o padrão IEC 60559:1989 (IEEE 754) para aritmética de ponto flutuante binário.

Este artigo consiste nas seguintes seções:

System.Single fornece métodos para comparar instâncias desse tipo, converter o valor de uma instância em sua representação de cadeia de caracteres e converter a representação de cadeia de caracteres de um número em uma instância desse tipo. Para obter informações sobre como os códigos de especificação de formato controlam a representação de cadeia de caracteres de tipos de valor, consulte Tipos de formatação, cadeias de caracteres de formato numérico padrão e cadeias de caracteres de formato numérico personalizado.

Representação de ponto flutuante e precisão

O Single tipo de dados armazena valores de ponto flutuante de precisão única em um formato binário de 32 bits, conforme mostrado na tabela a seguir:

Parte Bits
Significand ou mantissa 0-22
Exponent 23-30
Sinal (0 = positivo, 1 = negativo) 31

Assim como frações decimais não podem representar precisamente alguns valores fracionários (como 1/3 ou Math.PI), as frações binárias não podem representar alguns valores fracionários. Por exemplo, 2/10, que é representado precisamente por .2 como uma fração decimal, é representado por .0011111001001100 como uma fração binária, com o padrão "1100" repetindo ao infinito. Nesse caso, o valor de ponto flutuante fornece uma representação imprecisa do número que ele representa. Executar operações matemáticas adicionais no valor de ponto flutuante original geralmente aumenta sua falta de precisão. Por exemplo, se você comparar os resultados da multiplicação de .3 por 10 e adicionar .3 a 0,3 nove vezes, verá que a adição produz o resultado menos preciso, pois envolve oito operações a mais do que a multiplicação. Observe que essa disparidade é aparente somente se você exibir os dois Single valores usando a cadeia de caracteres de formato numérico padrão "R", que, se necessário, exibe todos os 9 dígitos de precisão compatíveis com o Single tipo.

using System;

public class Example
{
   public static void Main()
   {
      Single value = .2f;
      Single result1 = value * 10f;
      Single result2 = 0f;
      for (int ctr = 1; ctr <= 10; ctr++)
         result2 += value;

      Console.WriteLine(".2 * 10:           {0:R}", result1);
      Console.WriteLine(".2 Added 10 times: {0:R}", result2);
   }
}
// The example displays the following output:
//       .2 * 10:           2
//       .2 Added 10 times: 2.00000024
let value = 0.2f
let result1 = value * 10f
let mutable result2 = 0f
for _ = 1 to 10 do
    result2 <- result2 + value

printfn $".2 * 10:           {result1:R}"
printfn $".2 Added 10 times: {result2:R}"
// The example displays the following output:
//       .2 * 10:           2
//       .2 Added 10 times: 2.00000024
Module Example
   Public Sub Main()
      Dim value As Single = .2
      Dim result1 As Single = value * 10
      Dim result2 As Single
      For ctr As Integer = 1 To 10
         result2 += value
      Next
      Console.WriteLine(".2 * 10:           {0:R}", result1)
      Console.WriteLine(".2 Added 10 times: {0:R}", result2)
   End Sub
End Module
' The example displays the following output:
'       .2 * 10:           2
'       .2 Added 10 times: 2.00000024

Como alguns números não podem ser representados exatamente como valores binários fracionários, os números de ponto flutuante só podem aproximar números reais.

Todos os números de ponto flutuante têm um número limitado de dígitos significativos, o que também determina com que precisão um valor de ponto flutuante aproxima um número real. Um Single valor tem até 7 dígitos decimais de precisão, embora um máximo de 9 dígitos seja mantido internamente. Isso significa que algumas operações de ponto flutuante podem não ter a precisão para alterar um valor de ponto flutuante. O exemplo a seguir define um valor de ponto flutuante de precisão única grande e adiciona o produto de Single.Epsilon e um quadrilhão a ele. No entanto, o produto é muito pequeno para modificar o valor de ponto flutuante original. Seu dígito menos significativo é milésimos, enquanto o dígito mais significativo no produto é 10-30.

using System;

public class Example
{
   public static void Main()
   {
      Single value = 123.456f;
      Single additional = Single.Epsilon * 1e15f;
      Console.WriteLine($"{value} + {additional} = {value + additional}");
   }
}
// The example displays the following output:
//    123.456 + 1.401298E-30 = 123.456
open System

let value = 123.456f
let additional = Single.Epsilon * 1e15f
printfn $"{value} + {additional} = {value + additional}"
// The example displays the following output:
//    123.456 + 1.401298E-30 = 123.456
Module Example
   Public Sub Main()
      Dim value As Single = 123.456
      Dim additional As Single = Single.Epsilon * 1e15
      Console.WriteLine($"{value} + {additional} = {value + additional}")
   End Sub
End Module
' The example displays the following output:
'   123.456 + 1.401298E-30 = 123.456

A precisão limitada de um número de ponto flutuante tem várias consequências:

  • Dois números de ponto flutuante que pareçam iguais para uma determinada precisão podem não ser comparados como iguais porque seus dígitos menos significantes são diferentes. No exemplo a seguir, uma série de números é adicionada e seu total é comparado com o total esperado. Embora os dois valores pareçam ser os mesmos, uma chamada para o Equals método indica que eles não são.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Single[] values = { 10.01f, 2.88f, 2.88f, 2.88f, 9.0f };
          Single result = 27.65f;
          Single total = 0f;
          foreach (var value in values)
             total += value;
    
          if (total.Equals(result))
             Console.WriteLine("The sum of the values equals the total.");
          else
             Console.WriteLine("The sum of the values ({0}) does not equal the total ({1}).",
                               total, result); 
       }
    }
    // The example displays the following output:
    //      The sum of the values (27.65) does not equal the total (27.65).   
    //
    // If the index items in the Console.WriteLine statement are changed to {0:R},
    // the example displays the following output:
    //       The sum of the values (27.6500015) does not equal the total (27.65).
    
    let values = [| 10.01f; 2.88f; 2.88f; 2.88f; 9f |]
    let result = 27.65f
    let mutable total = 0f
    for value in values do
        total <- total + value
    
    if total.Equals result then
        printfn "The sum of the values equals the total."
    else
        printfn "The sum of the values ({total}) does not equal the total ({result})."
    // The example displays the following output:
    //      The sum of the values (27.65) does not equal the total (27.65).   
    //
    // If the index items in the Console.WriteLine statement are changed to {0:R},
    // the example displays the following output:
    //       The sum of the values (27.6500015) does not equal the total (27.65).
    
    Module Example
       Public Sub Main()
          Dim values() As Single = { 10.01, 2.88, 2.88, 2.88, 9.0 }
          Dim result As Single = 27.65
          Dim total As Single
          For Each value In values
             total += value
          Next
          If total.Equals(result) Then
             Console.WriteLine("The sum of the values equals the total.")
          Else
             Console.WriteLine("The sum of the values ({0}) does not equal the total ({1}).",
                               total, result) 
          End If     
       End Sub
    End Module
    ' The example displays the following output:
    '      The sum of the values (27.65) does not equal the total (27.65).   
    '
    ' If the index items in the Console.WriteLine statement are changed to {0:R},
    ' the example displays the following output:
    '       The sum of the values (27.639999999999997) does not equal the total (27.64).
    

    Se você alterar os itens de formato na Console.WriteLine(String, Object, Object) instrução de {0} e {1} para {0:R} e {1:R} para exibir todos os dígitos significativos dos dois Single valores, fica claro que os dois valores são diferentes devido à perda de precisão durante as operações de adição. Nesse caso, o problema pode ser resolvido chamando o Math.Round(Double, Int32) método para arredondar os Single valores para a precisão desejada antes de executar a comparação.

  • Uma operação matemática ou de comparação que usa um número de ponto flutuante pode não produzir o mesmo resultado se um número decimal for usado, pois o número de ponto flutuante binário pode não ser igual ao número decimal. Um exemplo anterior ilustrava isso exibindo o resultado da multiplicação de 0,3 por 10 e da adição de 0,3 a 0,3 nove vezes.

    Quando a precisão em operações numéricas com valores fracionários for importante, use o Decimal tipo em vez do Single tipo . Quando a precisão em operações numéricas com valores integrais além do intervalo dos Int64 tipos ou UInt64 for importante, use o BigInteger tipo .

  • Um valor poderá não ser de ida e volta se um número de ponto flutuante estiver envolvido. Um valor será chamado de ida e volta se uma operação converter um número de ponto flutuante original em outro formulário, uma operação inversa transformar o formulário convertido de volta em um número de ponto flutuante e o número de ponto flutuante final for igual ao número de ponto flutuante original. A viagem de ida e volta pode falhar porque um ou mais dígitos menos significativos são perdidos ou alterados em uma conversão. No exemplo a seguir, três Single valores são convertidos em cadeias de caracteres e salvos em um arquivo. Como mostra a saída, embora os valores pareçam idênticos, os valores restaurados não são iguais aos valores originais.

    using System;
    using System.IO;
    
    public class Example
    {
       public static void Main()
       {
          StreamWriter sw = new StreamWriter(@".\Singles.dat");
          Single[] values = { 3.2f/1.11f, 1.0f/3f, (float) Math.PI };
          for (int ctr = 0; ctr < values.Length; ctr++) {
             sw.Write(values[ctr].ToString());
             if (ctr != values.Length - 1)
                sw.Write("|");
          }      
          sw.Close();
          
          Single[] restoredValues = new Single[values.Length];
          StreamReader sr = new StreamReader(@".\Singles.dat");
          string temp = sr.ReadToEnd();
          string[] tempStrings = temp.Split('|');
          for (int ctr = 0; ctr < tempStrings.Length; ctr++)
             restoredValues[ctr] = Single.Parse(tempStrings[ctr]);   
    
          for (int ctr = 0; ctr < values.Length; ctr++)
             Console.WriteLine("{0} {2} {1}", values[ctr], 
                               restoredValues[ctr],
                               values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>");
       }
    }
    // The example displays the following output:
    //       2.882883 <> 2.882883
    //       0.3333333 <> 0.3333333
    //       3.141593 <> 3.141593
    
    open System
    open System.IO
    
    let values = [| 3.2f / 1.11f; 1f / 3f; MathF.PI |]
    
    do
        use sw = new StreamWriter(@".\Singles.dat")
        for i = 0 to values.Length - 1 do
            sw.Write(string values[i])
            if i <> values.Length - 1 then
                sw.Write "|"
    
    let restoredValues =
        use sr = new StreamReader(@".\Singles.dat")
        sr.ReadToEnd().Split '|'
        |> Array.map Single.Parse
    
    for i = 0 to values.Length - 1 do
        printfn $"""{values[i]} {if values[i].Equals restoredValues[i] then "=" else "<>"} {restoredValues[i]}"""
                        
    // The example displays the following output:
    //       2.882883 <> 2.882883
    //       0.3333333 <> 0.3333333
    //       3.141593 <> 3.141593
    
    Imports System.IO
    
    Module Example
       Public Sub Main()
          Dim sw As New StreamWriter(".\Singles.dat")
          Dim values() As Single = { 3.2/1.11, 1.0/3, CSng(Math.PI)  }
          For ctr As Integer = 0 To values.Length - 1
             sw.Write(values(ctr).ToString())
             If ctr <> values.Length - 1 Then sw.Write("|")
          Next      
          sw.Close()
          
          Dim restoredValues(values.Length - 1) As Single
          Dim sr As New StreamReader(".\Singles.dat")
          Dim temp As String = sr.ReadToEnd()
          Dim tempStrings() As String = temp.Split("|"c)
          For ctr As Integer = 0 To tempStrings.Length - 1
             restoredValues(ctr) = Single.Parse(tempStrings(ctr))   
          Next 
    
          For ctr As Integer = 0 To values.Length - 1
             Console.WriteLine("{0} {2} {1}", values(ctr), 
                               restoredValues(ctr),
                               If(values(ctr).Equals(restoredValues(ctr)), "=", "<>"))
          Next
       End Sub
    End Module
    ' The example displays the following output:
    '        2.882883 <> 2.882883
    '        0.3333333 <> 0.3333333
    '        3.141593 <> 3.141593
    

    Nesse caso, os valores podem ser arredondados com êxito usando a cadeia de caracteres de formato numérico padrão "G9" para preservar a precisão total dos Single valores, como mostra o exemplo a seguir.

    using System;
    using System.IO;
    
    public class Example
    {
       public static void Main()
       {
          StreamWriter sw = new StreamWriter(@".\Singles.dat");
          Single[] values = { 3.2f/1.11f, 1.0f/3f, (float) Math.PI };
          for (int ctr = 0; ctr < values.Length; ctr++) 
             sw.Write("{0:G9}{1}", values[ctr], ctr < values.Length - 1 ? "|" : "" );
          
          sw.Close();
          
          Single[] restoredValues = new Single[values.Length];
          StreamReader sr = new StreamReader(@".\Singles.dat");
          string temp = sr.ReadToEnd();
          string[] tempStrings = temp.Split('|');
          for (int ctr = 0; ctr < tempStrings.Length; ctr++)
             restoredValues[ctr] = Single.Parse(tempStrings[ctr]);   
    
          for (int ctr = 0; ctr < values.Length; ctr++)
             Console.WriteLine("{0} {2} {1}", values[ctr], 
                               restoredValues[ctr],
                               values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>");
       }
    }
    // The example displays the following output:
    //       2.882883 = 2.882883
    //       0.3333333 = 0.3333333
    //       3.141593 = 3.141593
    
    open System
    open System.IO
    
    let values = [| 3.2f / 1.11f; 1f / 3f; MathF.PI |]
    
    do
        use sw = new StreamWriter(@".\Singles.dat")
        for i = 0 to values.Length - 1 do
            sw.Write $"""{values[i]:G9}{if i < values.Length - 1 then "|" else ""}"""
        
        
    let restoredValues =
        use sr = new StreamReader(@".\Singles.dat")
        sr.ReadToEnd().Split '|'
        |> Array.map Single.Parse
    
    for i = 0 to values.Length - 1 do
        printfn $"""{values[i]} {if values[i].Equals restoredValues[i] then "=" else "<>"} {restoredValues[i]}"""
    // The example displays the following output:
    //       2.882883 = 2.882883
    //       0.3333333 = 0.3333333
    //       3.141593 = 3.141593
    
    Imports System.IO
    
    Module Example
       Public Sub Main()
          Dim sw As New StreamWriter(".\Singles.dat")
          Dim values() As Single = { 3.2/1.11, 1.0/3, CSng(Math.PI)  }
          For ctr As Integer = 0 To values.Length - 1
             sw.Write("{0:G9}{1}", values(ctr), 
                      If(ctr < values.Length - 1, "|", ""))
          Next      
          sw.Close()
          
          Dim restoredValues(values.Length - 1) As Single
          Dim sr As New StreamReader(".\Singles.dat")
          Dim temp As String = sr.ReadToEnd()
          Dim tempStrings() As String = temp.Split("|"c)
          For ctr As Integer = 0 To tempStrings.Length - 1
             restoredValues(ctr) = Single.Parse(tempStrings(ctr))   
          Next 
    
          For ctr As Integer = 0 To values.Length - 1
             Console.WriteLine("{0} {2} {1}", values(ctr), 
                               restoredValues(ctr),
                               If(values(ctr).Equals(restoredValues(ctr)), "=", "<>"))
          Next
       End Sub
    End Module
    ' The example displays the following output:
    '       2.882883 = 2.882883
    '       0.3333333 = 0.3333333
    '       3.141593 = 3.141593
    
  • Single os valores têm menos precisão do que Double os valores. Um Single valor que é convertido em um aparentemente equivalente Double geralmente não é igual ao valor devido a Double diferenças de precisão. No exemplo a seguir, o resultado de operações de divisão idênticas é atribuído a um Double valor e um Single valor . Depois que o Single valor é convertido em um Double, uma comparação dos dois valores mostra que eles são diferentes.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Double value1 = 1/3.0;
          Single sValue2 = 1/3.0f;
          Double value2 = (Double) sValue2;
          Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2,
                                              value1.Equals(value2));
       }
    }
    // The example displays the following output:
    //        0.33333333333333331 = 0.3333333432674408: False
    
    open System
    
    let value1 = 1. / 3.
    let sValue2 = 1f /3f
    
    let value2 = double sValue2
    printfn $"{value1:R} = {value2:R}: {value1.Equals value2}"
    // The example displays the following output:
    //        0.33333333333333331 = 0.3333333432674408: False
    
    Module Example
       Public Sub Main()
          Dim value1 As Double = 1/3
          Dim sValue2 As Single = 1/3
          Dim value2 As Double = CDbl(sValue2)
          Console.WriteLine("{0} = {1}: {2}", value1, value2, value1.Equals(value2))
       End Sub
    End Module
    ' The example displays the following output:
    '       0.33333333333333331 = 0.3333333432674408: False
    

    Para evitar esse problema, use o Double tipo de dados no lugar do tipo de Single dados ou use o Round método para que ambos os valores tenham a mesma precisão.

Testando igualdade

Para serem considerados iguais, dois Single valores devem representar valores idênticos. No entanto, devido a diferenças de precisão entre valores ou devido a uma perda de precisão por um ou ambos os valores, os valores de ponto flutuante que devem ser idênticos geralmente se tornam diferentes devido a diferenças em seus dígitos menos significativos. Como resultado, chama o Equals método para determinar se dois valores são iguais ou chamadas para o CompareTo método para determinar a relação entre dois Single valores, geralmente geram resultados inesperados. Isso é evidente no exemplo a seguir, em que dois valores aparentemente iguais Single são diferentes, pois o primeiro valor tem 7 dígitos de precisão, enquanto o segundo valor tem 9.

using System;

public class Example
{
   public static void Main()
   {
      float value1 = .3333333f;
      float value2 = 1.0f/3;
      Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2));
   }
}
// The example displays the following output:
//        0.3333333 = 0.333333343: False
let value1 = 0.3333333f
let value2 = 1f / 3f
printfn $"{value1:R} = {value2:R}: {value1.Equals value2}"
// The example displays the following output:
//        0.3333333 = 0.333333343: False
Module Example
   Public Sub Main()
      Dim value1 As Single = .3333333
      Dim value2 As Single = 1/3
      Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2))
   End Sub
End Module
' The example displays the following output:
'       0.3333333 = 0.333333343: False

Valores calculados que seguem caminhos de código diferentes e que são manipulados de maneiras diferentes geralmente se mostram diferentes. No exemplo a seguir, um Single valor é quadrado e, em seguida, a raiz quadrada é calculada para restaurar o valor original. Um segundo Single é multiplicado por 3,51 e ao quadrado antes que a raiz quadrada do resultado seja dividida por 3,51 para restaurar o valor original. Embora os dois valores pareçam ser idênticos, uma chamada para o Equals(Single) método indica que eles não são iguais. Usar a cadeia de caracteres de formato padrão "G9" para retornar uma cadeia de caracteres de resultado que exibe todos os dígitos significativos de cada Single valor mostra que o segundo valor é .0000000000001 menor que o primeiro.

using System;

public class Example
{
   public static void Main()
   {
      float value1 = 10.201438f;
      value1 = (float) Math.Sqrt((float) Math.Pow(value1, 2));
      float value2 = (float) Math.Pow((float) value1 * 3.51f, 2);
      value2 = ((float) Math.Sqrt(value2)) / 3.51f;
      Console.WriteLine("{0} = {1}: {2}\n", 
                        value1, value2, value1.Equals(value2)); 
      Console.WriteLine("{0:G9} = {1:G9}", value1, value2); 
   }
}
// The example displays the following output:
//       10.20144 = 10.20144: False
//       
//       10.201438 = 10.2014389
let value1 = 
    10.201438f ** 2f
    |> sqrt

let value2 =
   ((value1 * 3.51f) ** 2f |> sqrt) / 3.51f

printfn $"{value1} = {value2}: {value1.Equals value2}\n" 
printfn $"{value1:G9} = {value2:G9}"
// The example displays the following output:
//       10.20144 = 10.20144: False
//       
//       10.201438 = 10.2014389
Module Example
   Public Sub Main()
      Dim value1 As Single = 10.201438
      value1 = CSng(Math.Sqrt(CSng(Math.Pow(value1, 2))))
      Dim value2 As Single = CSng(Math.Pow(value1 * CSng(3.51), 2))
      value2 = CSng(Math.Sqrt(value2) / CSng(3.51))
      Console.WriteLine("{0} = {1}: {2}", 
                        value1, value2, value1.Equals(value2)) 
      Console.WriteLine()
      Console.WriteLine("{0:G9} = {1:G9}", value1, value2) 
   End Sub
End Module
' The example displays the following output:
'       10.20144 = 10.20144: False
'       
'       10.201438 = 10.2014389

Nos casos em que uma perda de precisão provavelmente afetará o resultado de uma comparação, você pode usar as seguintes técnicas em vez de chamar o Equals método ou CompareTo :

  • Chame o Math.Round método para garantir que ambos os valores tenham a mesma precisão. O exemplo a seguir modifica um exemplo anterior para usar essa abordagem para que dois valores fracionários sejam equivalentes.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          float value1 = .3333333f;
          float value2 = 1.0f/3;
          int precision = 7;
          value1 = (float) Math.Round(value1, precision);
          value2 = (float) Math.Round(value2, precision);
          Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2));
       }
    }
    // The example displays the following output:
    //        0.3333333 = 0.3333333: True
    
    open System
    
    let value1 = 0.3333333f
    let value2 = 1f / 3f
    let precision = 7
    let value1r = Math.Round(float value1, precision) |> float32
    let value2r = Math.Round(float value2, precision) |> float32
    printfn $"{value1:R} = {value2:R}: {value1.Equals value2}"
    // The example displays the following output:
    //        0.3333333 = 0.3333333: True
    
    Module Example
       Public Sub Main()
          Dim value1 As Single = .3333333
          Dim value2 As Single = 1/3
          Dim precision As Integer = 7
          value1 = CSng(Math.Round(value1, precision))
          value2 = CSng(Math.Round(value2, precision))
          Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2))
       End Sub
    End Module
    ' The example displays the following output:
    '       0.3333333 = 0.3333333: True
    

    O problema de precisão ainda se aplica ao arredondamento de valores de ponto médio. Para obter mais informações, consulte o método Math.Round(Double, Int32, MidpointRounding).

  • Teste a igualdade aproximada em vez da igualdade. Essa técnica exige que você defina uma quantidade absoluta pela qual os dois valores podem ser diferentes, mas ainda sejam iguais, ou que você defina uma quantidade relativa pela qual o valor menor pode divergir do valor maior.

    Aviso

    Single.Epsilon às vezes é usado como uma medida absoluta da distância entre dois Single valores ao testar a igualdade. No entanto, Single.Epsilon mede o menor valor possível que pode ser adicionado ou subtraído de um Single cujo valor é zero. Para a maioria dos valores positivos e negativos Single , o valor de Single.Epsilon é muito pequeno para ser detectado. Portanto, exceto para valores que são zero, não recomendamos seu uso em testes de igualdade.

    O exemplo a seguir usa a última abordagem para definir um IsApproximatelyEqual método que testa a diferença relativa entre dois valores. Ele também contrasta o resultado de chamadas para o IsApproximatelyEqual método e o Equals(Single) método .

    using System;
    
    public class Example
    {
       public static void Main()
       {
          float one1 = .1f * 10;
          float one2 = 0f;
          for (int ctr = 1; ctr <= 10; ctr++)
             one2 += .1f;
    
          Console.WriteLine("{0:R} = {1:R}: {2}", one1, one2, one1.Equals(one2));
          Console.WriteLine("{0:R} is approximately equal to {1:R}: {2}", 
                            one1, one2, 
                            IsApproximatelyEqual(one1, one2, .000001f));   
       }
    
       static bool IsApproximatelyEqual(float value1, float value2, float epsilon)
       {
          // If they are equal anyway, just return True.
          if (value1.Equals(value2))
             return true;
    
          // Handle NaN, Infinity.
          if (Double.IsInfinity(value1) | Double.IsNaN(value1))
             return value1.Equals(value2);
          else if (Double.IsInfinity(value2) | Double.IsNaN(value2))
             return value1.Equals(value2);
    
          // Handle zero to avoid division by zero
          double divisor = Math.Max(value1, value2);
          if (divisor.Equals(0)) 
             divisor = Math.Min(value1, value2);
          
          return Math.Abs(value1 - value2)/divisor <= epsilon;           
       } 
    }
    // The example displays the following output:
    //       1 = 1.00000012: False
    //       1 is approximately equal to 1.00000012: True
    
    open System
    
    let isApproximatelyEqual value1 value2 epsilon =
        // If they are equal anyway, just return True.
        if value1.Equals value2 then 
            true
        // Handle NaN, Infinity.
        elif Single.IsInfinity value1 || Single.IsNaN value1 then
            value1.Equals value2
        elif Single.IsInfinity value2 || Single.IsNaN value2 then
            value1.Equals value2
        else
            // Handle zero to avoid division by zero
            let divisor = max value1 value2
            let divisor = 
                if divisor.Equals 0 then
                    min value1 value2
                else divisor
            abs (value1 - value2) / divisor <= epsilon           
    
    
    let one1 = 0.1f * 10f
    let mutable one2 = 0f
    for _ = 1 to 10 do
       one2 <- one2 + 0.1f
    
    printfn $"{one1:R} = {one2:R}: {one1.Equals one2}"
    printfn $"{one1:R} is approximately equal to {one2:R}: {isApproximatelyEqual one1 one2 0.000001f}" 
    // The example displays the following output:
    //       1 = 1.00000012: False
    //       1 is approximately equal to 1.00000012: True
    
    Module Example
       Public Sub Main()
          Dim one1 As Single = .1 * 10
          Dim one2 As Single = 0
          For ctr As Integer = 1 To 10
             one2 += CSng(.1)
          Next
          Console.WriteLine("{0:R} = {1:R}: {2}", one1, one2, one1.Equals(one2))
          Console.WriteLine("{0:R} is approximately equal to {1:R}: {2}", 
                            one1, one2, 
                            IsApproximatelyEqual(one1, one2, .000001))   
       End Sub
    
       Function IsApproximatelyEqual(value1 As Single, value2 As Single, 
                                     epsilon As Single) As Boolean
          ' If they are equal anyway, just return True.
          If value1.Equals(value2) Then Return True
          
          ' Handle NaN, Infinity.
          If Single.IsInfinity(value1) Or Single.IsNaN(value1) Then
             Return value1.Equals(value2)
          Else If Single.IsInfinity(value2) Or Single.IsNaN(value2)
             Return value1.Equals(value2)
          End If
          
          ' Handle zero to avoid division by zero
          Dim divisor As Single = Math.Max(value1, value2)
          If divisor.Equals(0) Then
             divisor = Math.Min(value1, value2)
          End If 
          
          Return Math.Abs(value1 - value2)/divisor <= epsilon           
       End Function
    End Module
    ' The example displays the following output:
    '       1 = 1.00000012: False
    '       1 is approximately equal to 1.00000012: True
    

Valores de ponto flutuante e exceções

Operações com valores de ponto flutuante não geram exceções, ao contrário das operações com tipos integrais, que geram exceções em casos de operações ilegais, como divisão por zero ou estouro. Em vez disso, nessas situações, o resultado de uma operação de ponto flutuante é zero, infinito positivo, infinito negativo ou não um número (NaN):

  • Se o resultado de uma operação de ponto flutuante for muito pequeno para o formato de destino, o resultado será zero. Isso pode ocorrer quando dois números de ponto flutuante muito pequenos são multiplicados, como mostra o exemplo a seguir.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          float value1 = 1.163287e-36f;
          float value2 = 9.164234e-25f;
          float result = value1 * value2;
          Console.WriteLine("{0} * {1} = {2}", value1, value2, result);
          Console.WriteLine("{0} = 0: {1}", result, result.Equals(0.0f));
       }
    }
    // The example displays the following output:
    //       1.163287E-36 * 9.164234E-25 = 0
    //       0 = 0: True
    
    let value1 = 1.163287e-36f
    let value2 = 9.164234e-25f
    let result = value1 * value2
    printfn $"{value1} * {value2} = {result}"
    printfn $"{result} = 0: {result.Equals(0f)}"
    // The example displays the following output:
    //       1.163287E-36 * 9.164234E-25 = 0
    //       0 = 0: True
    
    Module Example
       Public Sub Main()
          Dim value1 As Single = 1.163287e-36
          Dim value2 As Single = 9.164234e-25
          Dim result As Single = value1 * value2
          Console.WriteLine("{0} * {1} = {2:R}", value1, value2, result)
          Console.WriteLine("{0} = 0: {1}", result, result.Equals(0))
       End Sub
    End Module
    ' The example displays the following output:
    '       1.163287E-36 * 9.164234E-25 = 0
    '       0 = 0: True
    
  • Se a magnitude do resultado de uma operação de ponto flutuante exceder o intervalo do formato de destino, o resultado da operação será PositiveInfinity ou NegativeInfinity, conforme apropriado para o sinal do resultado. O resultado de uma operação que estoura Single.MaxValue é PositiveInfinitye o resultado de uma operação que estoura Single.MinValue é NegativeInfinity, como mostra o exemplo a seguir.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          float value1 = 3.065e35f;
          float value2 = 6.9375e32f;
          float result = value1 * value2;
          Console.WriteLine("PositiveInfinity: {0}", 
                             Single.IsPositiveInfinity(result));
          Console.WriteLine("NegativeInfinity: {0}\n", 
                            Single.IsNegativeInfinity(result));
    
          value1 = -value1;
          result = value1 * value2;
          Console.WriteLine("PositiveInfinity: {0}", 
                             Single.IsPositiveInfinity(result));
          Console.WriteLine("NegativeInfinity: {0}", 
                            Single.IsNegativeInfinity(result));
       }
    }                                                                 
    
    // The example displays the following output:
    //       PositiveInfinity: True
    //       NegativeInfinity: False
    //       
    //       PositiveInfinity: False
    //       NegativeInfinity: True
    
    open System
    
    let value1 = 3.065e35f
    let value2 = 6.9375e32f
    let result = value1 * value2
    printfn $"PositiveInfinity: {Single.IsPositiveInfinity result}" 
    printfn $"NegativeInfinity: {Single.IsNegativeInfinity result}\n"
    
    let value3 = -value1
    let result2 = value3 * value2
    printfn $"PositiveInfinity: {Single.IsPositiveInfinity result}" 
    printfn $"NegativeInfinity: {Single.IsNegativeInfinity result}" 
    
    // The example displays the following output:
    //       PositiveInfinity: True
    //       NegativeInfinity: False
    //       
    //       PositiveInfinity: False
    //       NegativeInfinity: True
    
    Module Example
       Public Sub Main()
          Dim value1 As Single = 3.065e35
          Dim value2 As Single = 6.9375e32
          Dim result As Single = value1 * value2
          Console.WriteLine("PositiveInfinity: {0}", 
                             Single.IsPositiveInfinity(result))
          Console.WriteLine("NegativeInfinity: {0}", 
                            Single.IsNegativeInfinity(result))
          Console.WriteLine()                  
          value1 = -value1
          result = value1 * value2
          Console.WriteLine("PositiveInfinity: {0}", 
                             Single.IsPositiveInfinity(result))
          Console.WriteLine("NegativeInfinity: {0}", 
                            Single.IsNegativeInfinity(result))
       End Sub
    End Module
    ' The example displays the following output:
    '       PositiveInfinity: True
    '       NegativeInfinity: False
    '       
    '       PositiveInfinity: False
    '       NegativeInfinity: True
    

    PositiveInfinity também resulta de uma divisão por zero com um dividendo positivo, e NegativeInfinity resulta de uma divisão por zero com um dividendo negativo.

  • Se uma operação de ponto flutuante for inválida, o resultado da operação será NaN. Por exemplo, os NaN resultados das seguintes operações:

    • Divisão por zero com um dividendo de zero. Observe que outros casos de divisão por zero resultam PositiveInfinity em ou NegativeInfinity.

    • Qualquer operação de ponto flutuante com entrada inválida. Por exemplo, tentar localizar a raiz quadrada de um valor negativo retorna NaN.

    • Qualquer operação com um argumento cujo valor é Single.NaN.

Conversões de tipo e a estrutura Única

A Single estrutura não define nenhum operador de conversão explícito ou implícito; em vez disso, as conversões são implementadas pelo compilador.

A tabela a seguir lista as possíveis conversões de um valor dos outros tipos numéricos primitivos em um Single valor, ela também indica se a conversão está ampliando ou restringindo e se o resultado Single pode ter menos precisão do que o valor original.

Conversão de Ampliação/restrição Possível perda de precisão
Byte Widening Não
Decimal Widening

Observe que o C# requer um operador de conversão.
Sim. Decimal dá suporte a 29 dígitos decimais de precisão; Single dá suporte a 9.
Double Estreitamento; Valores fora do intervalo são convertidos Double.NegativeInfinity em ou Double.PositiveInfinity. Sim. Double dá suporte a 17 dígitos decimais de precisão; Single dá suporte a 9.
Int16 Widening Não
Int32 Widening Sim. Int32 dá suporte a 10 dígitos decimais de precisão; Single dá suporte a 9.
Int64 Widening Sim. Int64 dá suporte a 19 dígitos decimais de precisão; Single dá suporte a 9.
SByte Widening Não
UInt16 Widening Não
UInt32 Widening Sim. UInt32 dá suporte a 10 dígitos decimais de precisão; Single dá suporte a 9.
UInt64 Widening Sim. Int64 dá suporte a 20 dígitos decimais de precisão; Single dá suporte a 9.

O exemplo a seguir converte o valor mínimo ou máximo de outros tipos numéricos primitivos em um Single valor .

using System;

public class Example
{
   public static void Main()
   {
      dynamic[] values = { Byte.MinValue, Byte.MaxValue, Decimal.MinValue,
                           Decimal.MaxValue, Double.MinValue, Double.MaxValue,
                           Int16.MinValue, Int16.MaxValue, Int32.MinValue,
                           Int32.MaxValue, Int64.MinValue, Int64.MaxValue,
                           SByte.MinValue, SByte.MaxValue, UInt16.MinValue,
                           UInt16.MaxValue, UInt32.MinValue, UInt32.MaxValue,
                           UInt64.MinValue, UInt64.MaxValue };
      float sngValue;
      foreach (var value in values) {
         if (value.GetType() == typeof(Decimal) ||
             value.GetType() == typeof(Double))
            sngValue = (float) value;
         else
            sngValue = value;
         Console.WriteLine("{0} ({1}) --> {2:R} ({3})",
                           value, value.GetType().Name,
                           sngValue, sngValue.GetType().Name);
      }
   }
}
// The example displays the following output:
//       0 (Byte) --> 0 (Single)
//       255 (Byte) --> 255 (Single)
//       -79228162514264337593543950335 (Decimal) --> -7.92281625E+28 (Single)
//       79228162514264337593543950335 (Decimal) --> 7.92281625E+28 (Single)
//       -1.79769313486232E+308 (Double) --> -Infinity (Single)
//       1.79769313486232E+308 (Double) --> Infinity (Single)
//       -32768 (Int16) --> -32768 (Single)
//       32767 (Int16) --> 32767 (Single)
//       -2147483648 (Int32) --> -2.14748365E+09 (Single)
//       2147483647 (Int32) --> 2.14748365E+09 (Single)
//       -9223372036854775808 (Int64) --> -9.223372E+18 (Single)
//       9223372036854775807 (Int64) --> 9.223372E+18 (Single)
//       -128 (SByte) --> -128 (Single)
//       127 (SByte) --> 127 (Single)
//       0 (UInt16) --> 0 (Single)
//       65535 (UInt16) --> 65535 (Single)
//       0 (UInt32) --> 0 (Single)
//       4294967295 (UInt32) --> 4.2949673E+09 (Single)
//       0 (UInt64) --> 0 (Single)
//       18446744073709551615 (UInt64) --> 1.84467441E+19 (Single)
open System

let values: obj list = 
    [ Byte.MinValue; Byte.MaxValue; Decimal.MinValue
      Decimal.MaxValue; Double.MinValue; Double.MaxValue
      Int16.MinValue; Int16.MaxValue; Int32.MinValue
      Int32.MaxValue; Int64.MinValue; Int64.MaxValue
      SByte.MinValue; SByte.MaxValue; UInt16.MinValue
      UInt16.MaxValue; UInt32.MinValue; UInt32.MaxValue
      UInt64.MinValue; UInt64.MaxValue ]

for value in values do
    let sngValue = 
        match value with
        | :? byte as v -> float32 v
        | :? decimal as v -> float32 v
        | :? double as v -> float32 v
        | :? int16 as v -> float32 v
        | :? int as v -> float32 v
        | :? int64 as v -> float32 v
        | :? int8 as v -> float32 v
        | :? uint16 as v -> float32 v
        | :? uint as v -> float32 v
        | :? uint64 as v -> float32 v
        | _ -> raise (NotImplementedException "Unknown Type")
    printfn $"{value} ({value.GetType().Name}) --> {sngValue:R} ({sngValue.GetType().Name})"
// The example displays the following output:
//       0 (Byte) --> 0 (Single)
//       255 (Byte) --> 255 (Single)
//       -79228162514264337593543950335 (Decimal) --> -7.92281625E+28 (Single)
//       79228162514264337593543950335 (Decimal) --> 7.92281625E+28 (Single)
//       -1.79769313486232E+308 (Double) --> -Infinity (Single)
//       1.79769313486232E+308 (Double) --> Infinity (Single)
//       -32768 (Int16) --> -32768 (Single)
//       32767 (Int16) --> 32767 (Single)
//       -2147483648 (Int32) --> -2.14748365E+09 (Single)
//       2147483647 (Int32) --> 2.14748365E+09 (Single)
//       -9223372036854775808 (Int64) --> -9.223372E+18 (Single)
//       9223372036854775807 (Int64) --> 9.223372E+18 (Single)
//       -128 (SByte) --> -128 (Single)
//       127 (SByte) --> 127 (Single)
//       0 (UInt16) --> 0 (Single)
//       65535 (UInt16) --> 65535 (Single)
//       0 (UInt32) --> 0 (Single)
//       4294967295 (UInt32) --> 4.2949673E+09 (Single)
//       0 (UInt64) --> 0 (Single)
//       18446744073709551615 (UInt64) --> 1.84467441E+19 (Single)
Module Example
   Public Sub Main()
      Dim values() As Object = { Byte.MinValue, Byte.MaxValue, Decimal.MinValue,
                                 Decimal.MaxValue, Double.MinValue, Double.MaxValue,
                                 Int16.MinValue, Int16.MaxValue, Int32.MinValue,
                                 Int32.MaxValue, Int64.MinValue, Int64.MaxValue,
                                 SByte.MinValue, SByte.MaxValue, UInt16.MinValue,
                                 UInt16.MaxValue, UInt32.MinValue, UInt32.MaxValue,
                                 UInt64.MinValue, UInt64.MaxValue }
      Dim sngValue As Single
      For Each value In values
         If value.GetType() = GetType(Double) Then
            sngValue = CSng(value)
         Else
            sngValue = value
         End If
         Console.WriteLine("{0} ({1}) --> {2:R} ({3})",
                           value, value.GetType().Name,
                           sngValue, sngValue.GetType().Name)
      Next
   End Sub
End Module
' The example displays the following output:
'       0 (Byte) --> 0 (Single)
'       255 (Byte) --> 255 (Single)
'       -79228162514264337593543950335 (Decimal) --> -7.92281625E+28 (Single)
'       79228162514264337593543950335 (Decimal) --> 7.92281625E+28 (Single)
'       -1.79769313486232E+308 (Double) --> -Infinity (Single)
'       1.79769313486232E+308 (Double) --> Infinity (Single)
'       -32768 (Int16) --> -32768 (Single)
'       32767 (Int16) --> 32767 (Single)
'       -2147483648 (Int32) --> -2.14748365E+09 (Single)
'       2147483647 (Int32) --> 2.14748365E+09 (Single)
'       -9223372036854775808 (Int64) --> -9.223372E+18 (Single)
'       9223372036854775807 (Int64) --> 9.223372E+18 (Single)
'       -128 (SByte) --> -128 (Single)
'       127 (SByte) --> 127 (Single)
'       0 (UInt16) --> 0 (Single)
'       65535 (UInt16) --> 65535 (Single)
'       0 (UInt32) --> 0 (Single)
'       4294967295 (UInt32) --> 4.2949673E+09 (Single)
'       0 (UInt64) --> 0 (Single)
'       18446744073709551615 (UInt64) --> 1.84467441E+19 (Single)

Além disso, os Double valores Double.NaN, Double.PositiveInfinitye Double.NegativeInfinity convertem em Single.NaN, Single.PositiveInfinitye Single.NegativeInfinity, respectivamente.

Observe que a conversão do valor de alguns tipos numéricos em um Single valor pode envolver uma perda de precisão. Como o exemplo ilustra, uma perda de precisão é possível ao converter Decimalvalores Single , Double, Int32, Int64, UInt32e UInt64 em valores.

A conversão de um Single valor em um Double é uma conversão de expansão. A conversão poderá resultar em uma perda de precisão se o Double tipo não tiver uma representação precisa para o Single valor.

A conversão de um Single valor em um valor de qualquer tipo de dados numérico primitivo diferente de um Double é uma conversão de restrição e requer um operador de conversão (em C#) ou um método de conversão (no Visual Basic). Os valores que estão fora do intervalo do tipo de dados de destino, que são definidos pelas propriedades e MaxValue do tipo de MinValue destino, se comportam conforme mostrado na tabela a seguir.

Tipo de destino Resultado
Qualquer tipo integral Uma OverflowException exceção se a conversão ocorrer em um contexto verificado.

Se a conversão ocorrer em um contexto desmarcado (o padrão em C#), a operação de conversão terá êxito, mas o valor estourará.
Decimal Uma OverflowException exceção,

Além disso, Single.NaN, Single.PositiveInfinitye Single.NegativeInfinity lançam um OverflowException para conversões em inteiros em um contexto verificado, mas esses valores transbordam quando convertidos em inteiros em um contexto desmarcado. Para conversões em Decimal, eles sempre geram um OverflowException. Para conversões em Double, elas convertem em Double.NaN, Double.PositiveInfinitye Double.NegativeInfinity, respectivamente.

Observe que uma perda de precisão pode resultar da conversão de um Single valor em outro tipo numérico. No caso de conversão de valores não integrais Single , como mostra a saída do exemplo, o componente fracionário é perdido quando o Single valor é arredondado (como no Visual Basic) ou truncado (como em C# e F#). Para conversões em Decimal valores, o Single valor pode não ter uma representação precisa no tipo de dados de destino.

O exemplo a seguir converte vários Single valores em vários outros tipos numéricos. As conversões ocorrem em um contexto verificado no Visual Basic (o padrão), em C# (devido ao palavra-chave verificado) e em F# (devido à open Checked instrução ). A saída do exemplo mostra o resultado de conversões em um contexto desmarcado verificado. Você pode executar conversões em um contexto desmarcado no Visual Basic compilando com a opção do /removeintchecks+ compilador, em C# comentando a checked instrução e em F# comentando a instrução open Checked .

using System;

public class Example
{
   public static void Main()
   {
      float[] values = { Single.MinValue, -67890.1234f, -12345.6789f,
                         12345.6789f, 67890.1234f, Single.MaxValue,
                         Single.NaN, Single.PositiveInfinity,
                         Single.NegativeInfinity };
      checked {
         foreach (var value in values) {
            try {
                Int64 lValue = (long) value;
                Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
                                  value, value.GetType().Name,
                                  lValue, lValue.GetType().Name);
            }
            catch (OverflowException) {
               Console.WriteLine("Unable to convert {0} to Int64.", value);
            }
            try {
                UInt64 ulValue = (ulong) value;
                Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
                                  value, value.GetType().Name,
                                  ulValue, ulValue.GetType().Name);
            }
            catch (OverflowException) {
               Console.WriteLine("Unable to convert {0} to UInt64.", value);
            }
            try {
                Decimal dValue = (decimal) value;
                Console.WriteLine("{0} ({1}) --> {2} ({3})",
                                  value, value.GetType().Name,
                                  dValue, dValue.GetType().Name);
            }
            catch (OverflowException) {
               Console.WriteLine("Unable to convert {0} to Decimal.", value);
            }

            Double dblValue = value;
            Console.WriteLine("{0} ({1}) --> {2} ({3})",
                              value, value.GetType().Name,
                              dblValue, dblValue.GetType().Name);
            Console.WriteLine();
         }
      }
   }
}
// The example displays the following output for conversions performed
// in a checked context:
//       Unable to convert -3.402823E+38 to Int64.
//       Unable to convert -3.402823E+38 to UInt64.
//       Unable to convert -3.402823E+38 to Decimal.
//       -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
//
//       -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
//       Unable to convert -67890.13 to UInt64.
//       -67890.13 (Single) --> -67890.12 (Decimal)
//       -67890.13 (Single) --> -67890.125 (Double)
//
//       -12345.68 (Single) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
//       Unable to convert -12345.68 to UInt64.
//       -12345.68 (Single) --> -12345.68 (Decimal)
//       -12345.68 (Single) --> -12345.6787109375 (Double)
//
//       12345.68 (Single) --> 12345 (0x0000000000003039) (Int64)
//       12345.68 (Single) --> 12345 (0x0000000000003039) (UInt64)
//       12345.68 (Single) --> 12345.68 (Decimal)
//       12345.68 (Single) --> 12345.6787109375 (Double)
//
//       67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
//       67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
//       67890.13 (Single) --> 67890.12 (Decimal)
//       67890.13 (Single) --> 67890.125 (Double)
//
//       Unable to convert 3.402823E+38 to Int64.
//       Unable to convert 3.402823E+38 to UInt64.
//       Unable to convert 3.402823E+38 to Decimal.
//       3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
//
//       Unable to convert NaN to Int64.
//       Unable to convert NaN to UInt64.
//       Unable to convert NaN to Decimal.
//       NaN (Single) --> NaN (Double)
//
//       Unable to convert Infinity to Int64.
//       Unable to convert Infinity to UInt64.
//       Unable to convert Infinity to Decimal.
//       Infinity (Single) --> Infinity (Double)
//
//       Unable to convert -Infinity to Int64.
//       Unable to convert -Infinity to UInt64.
//       Unable to convert -Infinity to Decimal.
//       -Infinity (Single) --> -Infinity (Double)
// The example displays the following output for conversions performed
// in an unchecked context:
//       -3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       -3.402823E+38 (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
//       Unable to convert -3.402823E+38 to Decimal.
//       -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
//
//       -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
//       -67890.13 (Single) --> 18446744073709483726 (0xFFFFFFFFFFFEF6CE) (UInt64)
//       -67890.13 (Single) --> -67890.12 (Decimal)
//       -67890.13 (Single) --> -67890.125 (Double)
//
//       -12345.68 (Single) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
//       -12345.68 (Single) --> 18446744073709539271 (0xFFFFFFFFFFFFCFC7) (UInt64)
//       -12345.68 (Single) --> -12345.68 (Decimal)
//       -12345.68 (Single) --> -12345.6787109375 (Double)
//
//       12345.68 (Single) --> 12345 (0x0000000000003039) (Int64)
//       12345.68 (Single) --> 12345 (0x0000000000003039) (UInt64)
//       12345.68 (Single) --> 12345.68 (Decimal)
//       12345.68 (Single) --> 12345.6787109375 (Double)
//
//       67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
//       67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
//       67890.13 (Single) --> 67890.12 (Decimal)
//       67890.13 (Single) --> 67890.125 (Double)
//
//       3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       3.402823E+38 (Single) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert 3.402823E+38 to Decimal.
//       3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
//
//       NaN (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       NaN (Single) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert NaN to Decimal.
//       NaN (Single) --> NaN (Double)
//
//       Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       Infinity (Single) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert Infinity to Decimal.
//       Infinity (Single) --> Infinity (Double)
//
//       -Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       -Infinity (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
//       Unable to convert -Infinity to Decimal.
//       -Infinity (Single) --> -Infinity (Double)
open System
open Checked

let values = 
    [ Single.MinValue; -67890.1234f; -12345.6789f
      12345.6789f; 67890.1234f; Single.MaxValue
      Single.NaN; Single.PositiveInfinity
      Single.NegativeInfinity ]

for value in values do
    try
        let lValue = int64 value
        printfn $"{value} ({value.GetType().Name}) --> {lValue} (0x{lValue:X16}) ({lValue.GetType().Name})"
    with :? OverflowException ->
        printfn $"Unable to convert {value} to Int64."
    try
        let ulValue = uint64 value
        printfn $"{value} ({value.GetType().Name}) --> {ulValue} (0x{ulValue:X16}) ({ulValue.GetType().Name})"
    with :? OverflowException ->
        printfn $"Unable to convert {value} to UInt64."
    try
        let dValue = decimal value
        printfn $"{value} ({value.GetType().Name}) --> {dValue} ({dValue.GetType().Name})"
    with :? OverflowException ->
        printfn $"Unable to convert {value} to Decimal."

    let dblValue = double value
    printfn $"{value} ({value.GetType().Name}) --> {dblValue} ({dblValue.GetType().Name})\n"
// The example displays the following output for conversions performed
// in a checked context:
//       Unable to convert -3.402823E+38 to Int64.
//       Unable to convert -3.402823E+38 to UInt64.
//       Unable to convert -3.402823E+38 to Decimal.
//       -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
//
//       -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
//       Unable to convert -67890.13 to UInt64.
//       -67890.13 (Single) --> -67890.12 (Decimal)
//       -67890.13 (Single) --> -67890.125 (Double)
//
//       -12345.68 (Single) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
//       Unable to convert -12345.68 to UInt64.
//       -12345.68 (Single) --> -12345.68 (Decimal)
//       -12345.68 (Single) --> -12345.6787109375 (Double)
//
//       12345.68 (Single) --> 12345 (0x0000000000003039) (Int64)
//       12345.68 (Single) --> 12345 (0x0000000000003039) (UInt64)
//       12345.68 (Single) --> 12345.68 (Decimal)
//       12345.68 (Single) --> 12345.6787109375 (Double)
//
//       67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
//       67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
//       67890.13 (Single) --> 67890.12 (Decimal)
//       67890.13 (Single) --> 67890.125 (Double)
//
//       Unable to convert 3.402823E+38 to Int64.
//       Unable to convert 3.402823E+38 to UInt64.
//       Unable to convert 3.402823E+38 to Decimal.
//       3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
//
//       Unable to convert NaN to Int64.
//       Unable to convert NaN to UInt64.
//       Unable to convert NaN to Decimal.
//       NaN (Single) --> NaN (Double)
//
//       Unable to convert Infinity to Int64.
//       Unable to convert Infinity to UInt64.
//       Unable to convert Infinity to Decimal.
//       Infinity (Single) --> Infinity (Double)
//
//       Unable to convert -Infinity to Int64.
//       Unable to convert -Infinity to UInt64.
//       Unable to convert -Infinity to Decimal.
//       -Infinity (Single) --> -Infinity (Double)
// The example displays the following output for conversions performed
// in an unchecked context:
//       -3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       -3.402823E+38 (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
//       Unable to convert -3.402823E+38 to Decimal.
//       -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
//
//       -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
//       -67890.13 (Single) --> 18446744073709483726 (0xFFFFFFFFFFFEF6CE) (UInt64)
//       -67890.13 (Single) --> -67890.12 (Decimal)
//       -67890.13 (Single) --> -67890.125 (Double)
//
//       -12345.68 (Single) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
//       -12345.68 (Single) --> 18446744073709539271 (0xFFFFFFFFFFFFCFC7) (UInt64)
//       -12345.68 (Single) --> -12345.68 (Decimal)
//       -12345.68 (Single) --> -12345.6787109375 (Double)
//
//       12345.68 (Single) --> 12345 (0x0000000000003039) (Int64)
//       12345.68 (Single) --> 12345 (0x0000000000003039) (UInt64)
//       12345.68 (Single) --> 12345.68 (Decimal)
//       12345.68 (Single) --> 12345.6787109375 (Double)
//
//       67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
//       67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
//       67890.13 (Single) --> 67890.12 (Decimal)
//       67890.13 (Single) --> 67890.125 (Double)
//
//       3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       3.402823E+38 (Single) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert 3.402823E+38 to Decimal.
//       3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
//
//       NaN (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       NaN (Single) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert NaN to Decimal.
//       NaN (Single) --> NaN (Double)
//
//       Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       Infinity (Single) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert Infinity to Decimal.
//       Infinity (Single) --> Infinity (Double)
//
//       -Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       -Infinity (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
//       Unable to convert -Infinity to Decimal.
//       -Infinity (Single) --> -Infinity (Double)
Module Example
   Public Sub Main()
      Dim values() As Single = { Single.MinValue, -67890.1234, -12345.6789,
                                 12345.6789, 67890.1234, Single.MaxValue,
                                 Single.NaN, Single.PositiveInfinity,
                                 Single.NegativeInfinity }
      For Each value In values
         Try
             Dim lValue As Long = CLng(value)
             Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
                               value, value.GetType().Name,
                               lValue, lValue.GetType().Name)
         Catch e As OverflowException
            Console.WriteLine("Unable to convert {0} to Int64.", value)
         End Try
         Try
             Dim ulValue As UInt64 = CULng(value)
             Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
                               value, value.GetType().Name,
                               ulValue, ulValue.GetType().Name)
         Catch e As OverflowException
            Console.WriteLine("Unable to convert {0} to UInt64.", value)
         End Try
         Try
             Dim dValue As Decimal = CDec(value)
             Console.WriteLine("{0} ({1}) --> {2} ({3})",
                               value, value.GetType().Name,
                               dValue, dValue.GetType().Name)
         Catch e As OverflowException
            Console.WriteLine("Unable to convert {0} to Decimal.", value)
         End Try

         Dim dblValue As Double = value
         Console.WriteLine("{0} ({1}) --> {2} ({3})",
                           value, value.GetType().Name,
                           dblValue, dblValue.GetType().Name)
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output for conversions performed
' in a checked context:
'       Unable to convert -3.402823E+38 to Int64.
'       Unable to convert -3.402823E+38 to UInt64.
'       Unable to convert -3.402823E+38 to Decimal.
'       -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
'
'       -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
'       Unable to convert -67890.13 to UInt64.
'       -67890.13 (Single) --> -67890.12 (Decimal)
'       -67890.13 (Single) --> -67890.125 (Double)
'
'       -12345.68 (Single) --> -12346 (0xFFFFFFFFFFFFCFC6) (Int64)
'       Unable to convert -12345.68 to UInt64.
'       -12345.68 (Single) --> -12345.68 (Decimal)
'       -12345.68 (Single) --> -12345.6787109375 (Double)
'
'       12345.68 (Single) --> 12346 (0x000000000000303A) (Int64)
'       12345.68 (Single) --> 12346 (0x000000000000303A) (UInt64)
'       12345.68 (Single) --> 12345.68 (Decimal)
'       12345.68 (Single) --> 12345.6787109375 (Double)
'
'       67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
'       67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
'       67890.13 (Single) --> 67890.12 (Decimal)
'       67890.13 (Single) --> 67890.125 (Double)
'
'       Unable to convert 3.402823E+38 to Int64.
'       Unable to convert 3.402823E+38 to UInt64.
'       Unable to convert 3.402823E+38 to Decimal.
'       3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
'
'       Unable to convert NaN to Int64.
'       Unable to convert NaN to UInt64.
'       Unable to convert NaN to Decimal.
'       NaN (Single) --> NaN (Double)
'
'       Unable to convert Infinity to Int64.
'       Unable to convert Infinity to UInt64.
'       Unable to convert Infinity to Decimal.
'       Infinity (Single) --> Infinity (Double)
'
'       Unable to convert -Infinity to Int64.
'       Unable to convert -Infinity to UInt64.
'       Unable to convert -Infinity to Decimal.
'       -Infinity (Single) --> -Infinity (Double)
' The example displays the following output for conversions performed
' in an unchecked context:
'       -3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       -3.402823E+38 (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
'       Unable to convert -3.402823E+38 to Decimal.
'       -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
'
'       -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
'       -67890.13 (Single) --> 18446744073709483726 (0xFFFFFFFFFFFEF6CE) (UInt64)
'       -67890.13 (Single) --> -67890.12 (Decimal)
'       -67890.13 (Single) --> -67890.125 (Double)
'
'       -12345.68 (Single) --> -12346 (0xFFFFFFFFFFFFCFC6) (Int64)
'       -12345.68 (Single) --> 18446744073709539270 (0xFFFFFFFFFFFFCFC6) (UInt64)
'       -12345.68 (Single) --> -12345.68 (Decimal)
'       -12345.68 (Single) --> -12345.6787109375 (Double)
'
'       12345.68 (Single) --> 12346 (0x000000000000303A) (Int64)
'       12345.68 (Single) --> 12346 (0x000000000000303A) (UInt64)
'       12345.68 (Single) --> 12345.68 (Decimal)
'       12345.68 (Single) --> 12345.6787109375 (Double)
'
'       67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
'       67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
'       67890.13 (Single) --> 67890.12 (Decimal)
'       67890.13 (Single) --> 67890.125 (Double)
'
'       3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       3.402823E+38 (Single) --> 0 (0x0000000000000000) (UInt64)
'       Unable to convert 3.402823E+38 to Decimal.
'       3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
'
'       NaN (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       NaN (Single) --> 0 (0x0000000000000000) (UInt64)
'       Unable to convert NaN to Decimal.
'       NaN (Single) --> NaN (Double)
'
'       Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       Infinity (Single) --> 0 (0x0000000000000000) (UInt64)
'       Unable to convert Infinity to Decimal.
'       Infinity (Single) --> Infinity (Double)
'
'       -Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       -Infinity (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
'       Unable to convert -Infinity to Decimal.
'       -Infinity (Single) --> -Infinity (Double)

Para obter mais informações sobre a conversão de tipos numéricos, consulte Conversão de tipo no .NET Framework e Tabelas de Conversão de Tipo.

Funcionalidade de ponto flutuante

A Single estrutura e os tipos relacionados fornecem métodos para executar as seguintes categorias de operações:

  • Comparação de valores. Você pode chamar o Equals método para determinar se dois Single valores são iguais ou o CompareTo método para determinar a relação entre dois valores.

    A Single estrutura também dá suporte a um conjunto completo de operadores de comparação. Por exemplo, você pode testar a igualdade ou a desigualdade ou determinar se um valor é maior ou igual a outro valor. Se um dos operandos for um Double, o Single valor será convertido em um Double antes de executar a comparação. Se um dos operandos for um tipo integral, ele será convertido em um Single antes de executar a comparação. Embora sejam conversões de expansão, elas podem envolver uma perda de precisão.

    Aviso

    Devido a diferenças de precisão, dois Single valores que você espera que sejam iguais podem ser diferentes, o que afeta o resultado da comparação. Consulte a seção Teste de igualdade para obter mais informações sobre como comparar dois Single valores.

    Você também pode chamar os IsNaNmétodos , IsInfinityIsPositiveInfinity, e IsNegativeInfinity para testar esses valores especiais.

  • Operações matemáticas. Operações aritméticas comuns, como adição, subtração, multiplicação e divisão, são implementadas por compiladores de linguagem e instruções de CIL (Common Intermediate Language) e não por Single métodos. Se o outro operando em uma operação matemática for um Double, o Single será convertido em um Double antes de executar a operação e o resultado da operação também será um Double valor. Se o outro operando for um tipo integral, ele será convertido em um Single antes de executar a operação e o resultado da operação também será um Single valor.

    Você pode executar outras operações matemáticas chamando static métodos (Shared no Visual Basic) na System.Math classe . Eles incluem métodos adicionais comumente usados para aritmética (como , e ), geometria (como Math.Cos e Math.Sin) e cálculo (como Math.Log).Math.SqrtMath.SignMath.Abs Em todos os casos, o Single valor é convertido em um Double.

    Você também pode manipular os bits individuais em um Single valor. O BitConverter.GetBytes(Single) método retorna seu padrão de bits em uma matriz de bytes. Ao passar essa matriz de bytes para o BitConverter.ToInt32 método , você também pode preservar o Single padrão de bits do valor em um inteiro de 32 bits.

  • Arredondamento. O arredondamento geralmente é usado como uma técnica para reduzir o impacto das diferenças entre os valores causados por problemas de representação e precisão de ponto flutuante. Você pode arredondar um Single valor chamando o Math.Round método . No entanto, observe que o Single valor é convertido em um Double antes do método ser chamado e a conversão pode envolver uma perda de precisão.

  • Formatação. Você pode converter um Single valor em sua representação de cadeia de caracteres chamando o ToString método ou usando o recurso de formatação composta . Para obter informações sobre como as cadeias de caracteres de formato controlam a representação de cadeia de caracteres de valores de ponto flutuante, consulte os tópicos Cadeias de caracteres de formato numérico padrão e cadeias de caracteres de formato numérico personalizado .

  • Analisando cadeias de caracteres. Você pode converter a representação de cadeia de caracteres de um valor de ponto flutuante em um Single valor chamando o Parse método ou TryParse . Se a operação de análise falhar, o Parse método gerará uma exceção, enquanto o TryParse método retornará false.

  • Conversão de tipo. A Single estrutura fornece uma implementação de interface explícita para a interface , que dá suporte à IConvertible conversão entre dois tipos de dados de .NET Framework padrão. Os compiladores de linguagem também dão suporte à conversão implícita de valores para todos os outros tipos numéricos padrão, exceto para a conversão de Double em Single valores. A conversão de um valor de qualquer tipo numérico padrão diferente de um Double em um é uma Single conversão de expansão e não requer o uso de um operador de conversão ou método de conversão.

    No entanto, a conversão de valores inteiros de 32 bits e 64 bits pode envolver uma perda de precisão. A tabela a seguir lista as diferenças de precisão para tipos de 32 bits, 64 bits e Double :

    Tipo Precisão máxima (em dígitos decimais) Precisão interna (em dígitos decimais)
    Double 15 17
    Int32 e UInt32 10 10
    Int64 e UInt64 19 19
    Single 7 9

    O problema da precisão afeta Single com mais frequência os valores convertidos em Double valores. No exemplo a seguir, dois valores produzidos por operações de divisão idênticas são diferentes, pois um dos valores é um valor de ponto flutuante de precisão única convertido em um Double.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Double value1 = 1/3.0;
          Single sValue2 = 1/3.0f;
          Double value2 = (Double) sValue2;
          Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, 
                                              value1.Equals(value2));
       }
    }
    // The example displays the following output:
    //        0.33333333333333331 = 0.3333333432674408: False
    
    let value1 = 1. / 3.
    let sValue2 = 1f / 3f
    let value2 = double sValue2
    printfn $"{value1:R} = {value2:R}: {value1.Equals value2}"
    // The example displays the following output:
    //        0.33333333333333331 = 0.3333333432674408: False
    
    Module Example
       Public Sub Main()
          Dim value1 As Double = 1/3
          Dim sValue2 As Single = 1/3
          Dim value2 As Double = CDbl(sValue2)
          Console.WriteLine("{0} = {1}: {2}", value1, value2, value1.Equals(value2))
       End Sub
    End Module
    ' The example displays the following output:
    '       0.33333333333333331 = 0.3333333432674408: False
    

Campos

E

Representa a base logarítmica natural, especificada pela constante, e.

Epsilon

Representa o menor valor Single positivo maior que zero. Este campo é constante.

MaxValue

Representa o maior valor possível de Single. Este campo é constante.

MinValue

Representa o menor valor possível de Single. Este campo é constante.

NaN

Representa algo que não é um número (NaN). Este campo é constante.

NegativeInfinity

Representa o infinito negativo. Este campo é constante.

NegativeZero

Representa o número zero negativo (-0).

Pi

Representa a razão entre a circunferência de um círculo e seu diâmetro, especificada pela constante π.

PositiveInfinity

Representa infinito positivo. Este campo é constante.

Tau

Representa o número de radianos em um turno, especificado pela constante, τ.

Métodos

Abs(Single)

Calcula o absoluto de um valor.

Acos(Single)

Calcula o arco cosseno de um valor.

Acosh(Single)

Calcula o arco-cosseno hiperbólico de um valor.

AcosPi(Single)

Calcula o arco-cosseno de um valor e divide o resultado por pi.

Asin(Single)

Calcula o arco-seno de um valor.

Asinh(Single)

Calcula o arco-seno hiperbólico de um valor.

AsinPi(Single)

Calcula o arco-seno de um valor e divide o resultado por pi.

Atan(Single)

Calcula o arco tangente de um valor.

Atan2(Single, Single)

Calcula o arco tangente do quociente de dois valores.

Atan2Pi(Single, Single)

Calcula o arco tangente para o quociente de dois valores e divide o resultado por pi.

Atanh(Single)

Calcula o arco-tangente hiperbólico de um valor.

AtanPi(Single)

Calcula o arco tangente de um valor e divide o resultado por pi.

BitDecrement(Single)

Diminui um valor para o menor valor que compara menos do que um determinado valor.

BitIncrement(Single)

Incrementa um valor para o menor valor que compara maior que um determinado valor.

Cbrt(Single)

Calcula a raiz do cubo de um valor.

Ceiling(Single)

Calcula o teto de um valor.

Clamp(Single, Single, Single)

Fixa um valor a um valor mínimo inclusivo e máximo.

CompareTo(Object)

Compara esta instância a um objeto especificado e retorna um inteiro que indica se o valor desta instância é menor, igual ou maior que o valor do objeto especificado.

CompareTo(Single)

Compara essa instância a um número de ponto flutuante de precisão simples especificado e retorna um inteiro que indica se o valor dessa instância é menor que, igual a ou maior que o valor do número de ponto flutuante de precisão simples especificado.

CopySign(Single, Single)

Copia o sinal de um valor para o sinal de outro valor.

Cos(Single)

Calcula o cosseno de um valor.

Cosh(Single)

Calcula o cosseno hiperbólico de um valor.

CosPi(Single)

Calcula o cosseno de um valor que foi múltiplo por pi.

CreateChecked<TOther>(TOther)

Cria uma instância do tipo atual de um valor, gerando uma exceção de estouro para todos os valores que ficam fora do intervalo representável do tipo atual.

CreateSaturating<TOther>(TOther)

Cria uma instância do tipo atual de um valor, saturando todos os valores que ficam fora do intervalo representável do tipo atual.

CreateTruncating<TOther>(TOther)

Cria uma instância do tipo atual de um valor, truncando todos os valores que ficam fora do intervalo representável do tipo atual.

DegreesToRadians(Single)

Converte um determinado valor de graus em radianos.

Equals(Object)

Retorna um valor que indica se a instância é igual a um objeto especificado.

Equals(Single)

Retorna um valor que indica se essa instância e um objeto Single especificado representam o mesmo valor.

Exp(Single)

Cálculos gerados E para um determinado poder.

Exp10(Single)

Cálculos gerados 10 para um determinado poder.

Exp10M1(Single)

Cálculos gerados 10 para um determinado poder e subtrai um.

Exp2(Single)

Cálculos gerados 2 para um determinado poder.

Exp2M1(Single)

Cálculos gerados 2 para um determinado poder e subtrai um.

ExpM1(Single)

Cálculos gerados E para um determinado poder e subtrai um.

Floor(Single)

Calcula o piso de um valor.

FusedMultiplyAdd(Single, Single, Single)

Calcula a multiplicação-adição fundida de três valores.

GetHashCode()

Retorna o código hash para a instância.

GetTypeCode()

Retorna o TypeCode para tipo de valor Single.

Hypot(Single, Single)

Calcula a hipotenusa dado dois valores que representam os comprimentos dos lados mais curtos em um triângulo com ângulo direito.

Ieee754Remainder(Single, Single)

Calcula o restante de dois valores conforme especificado pelo IEEE 754.

ILogB(Single)

Calcula o logaritmo inteiro de um valor.

IsEvenInteger(Single)

Determina se um valor representa um número integral par.

IsFinite(Single)

Determina se o valor especificado é finito (zero, subnormal ou normal).

IsInfinity(Single)

Retorna um valor que indica se o número especificado é avaliado como infinito positivo ou negativo.

IsInteger(Single)

Determina se um valor representa um valor integral.

IsNaN(Single)

Retorna um valor que indica se o valor especificado não é um número (NaN).

IsNegative(Single)

Determina se o valor especificado é negativo.

IsNegativeInfinity(Single)

Retorna um valor que indica se o número especificado é avaliado quanto ao infinito negativo.

IsNormal(Single)

Determina se o valor especificado é normal.

IsOddInteger(Single)

Determina se um valor representa um número integral ímpar.

IsPositive(Single)

Determina se um valor é positivo.

IsPositiveInfinity(Single)

Retorna um valor que indica se o número especificado é avaliado quanto ao infinito positivo.

IsPow2(Single)

Determina se um valor é uma potência de dois.

IsRealNumber(Single)

Determina se um valor representa um número real.

IsSubnormal(Single)

Determina se o valor especificado é subnormal.

Lerp(Single, Single, Single)

Executa uma interpolação linear entre dois valores com base no peso fornecido.

Log(Single)

Calcula o natural (base-E logaritmo de um valor.

Log(Single, Single)

Calcula o logaritmo de um valor na base especificada.

Log10(Single)

Calcula o logaritmo de base 10 de um valor.

Log10P1(Single)

Calcula o logaritmo de base 10 de um valor mais um.

Log2(Single)

Calcula o log2 de um valor.

Log2P1(Single)

Calcula o logaritmo de base 2 de um valor mais um.

LogP1(Single)

Calcula o logaritmo natural (base-E) de um valor mais um.

Max(Single, Single)

Compara dois valores com a computação, que é maior.

MaxMagnitude(Single, Single)

Compara dois valores com a computação, que é maior.

MaxMagnitudeNumber(Single, Single)

Compara dois valores com a computação que tem a magnitude maior e retorna o outro valor se uma entrada for NaN.

MaxNumber(Single, Single)

Compara dois valores com a computação, que é maior e retorna o outro valor se uma entrada for NaN.

Min(Single, Single)

Compara dois valores com a computação que é menor.

MinMagnitude(Single, Single)

Compara dois valores com a computação que é menor.

MinMagnitudeNumber(Single, Single)

Compara dois valores com a computação que tem a magnitude menor e retorna o outro valor se uma entrada for NaN.

MinNumber(Single, Single)

Compara dois valores com a computação que é menor e retorna o outro valor se uma entrada é NaN.

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Analisa um intervalo de caracteres UTF-8 em um valor.

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Analisa um intervalo de caracteres UTF-8 em um valor.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Analisa um intervalo de caracteres em um valor.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Converte um intervalo de caracteres que contém a representação de cadeia de caracteres de um número em um formato específico da cultura e um estilo especificados para o número de ponto flutuante de precisão simples equivalente.

Parse(String)

Converte a representação da cadeia de caracteres de um número no número de ponto flutuante de precisão simples equivalente.

Parse(String, IFormatProvider)

Converte a representação de cadeia de caracteres de um número em um formato específico da cultura para o número de ponto flutuante de precisão simples equivalente.

Parse(String, NumberStyles)

Converte a representação de cadeia de caracteres de um número em um estilo especificado para o número de ponto flutuante de precisão simples equivalente.

Parse(String, NumberStyles, IFormatProvider)

Converte a representação de cadeia de caracteres de um número em um estilo e formato específico da cultura especificados em seu equivalente de número de ponto flutuante de precisão simples.

Pow(Single, Single)

Calcula um valor gerado para um determinado poder.

RadiansToDegrees(Single)

Converte um determinado valor de radianos em graus.

ReciprocalEstimate(Single)

Calcula uma estimativa da recíproca de um valor.

ReciprocalSqrtEstimate(Single)

Calcula uma estimativa da raiz quadrada recíproca de um valor.

RootN(Single, Int32)

Calcula a raiz n-th de um valor.

Round(Single)

Arredonda um valor para o inteiro mais próximo usando o modo de arredondamento padrão (ToEven).

Round(Single, Int32)

Arredonda um valor para um número especificado de dígitos fracionários usando o modo de arredondamento padrão (ToEven).

Round(Single, Int32, MidpointRounding)

Arredonda um valor para um número especificado de dígitos fracionários usando o modo de arredondamento padrão (ToEven).

Round(Single, MidpointRounding)

Arredonda um valor para o inteiro mais próximo usando o modo de arredondamento especificado.

ScaleB(Single, Int32)

Calcula o produto de um valor e seu radix base elevado à potência especificada.

Sign(Single)

Calcula o sinal de um valor.

Sin(Single)

Calcula o seno de um valor.

SinCos(Single)

Calcula o seno e o cosseno de um valor.

SinCosPi(Single)

Calcula o seno e o cosseno de um valor.

Sinh(Single)

Calcula o seno hiperbólico de um valor.

SinPi(Single)

Calcula o seno de um valor que foi multiplicado por pi.

Sqrt(Single)

Calcula a raiz quadrada de um valor.

Tan(Single)

Calcula a tangente de um valor.

Tanh(Single)

Calcula a tangente hiperbólica de um valor.

TanPi(Single)

Calcula a tangente de um valor que foi múltiplo por pi.

ToString()

Converte o valor numérico dessa instância na representação da cadeia de caracteres equivalente.

ToString(IFormatProvider)

Converte o valor numérico dessa instância na representação da cadeia de caracteres equivalente usando as informações de formato específicas da cultura.

ToString(String)

Converte o valor numérico dessa instância na representação da cadeia de caracteres equivalente usando o formato especificado.

ToString(String, IFormatProvider)

Converte o valor numérico dessa instância na representação da cadeia de caracteres equivalente usando o formato especificado e as informações de formato específicas da cultura especificada.

Truncate(Single)

Trunca um valor.

TryFormat(Span<Byte>, Int32, ReadOnlySpan<Char>, IFormatProvider)

Tenta formatar o valor da instância atual como UTF-8 no intervalo fornecido de bytes.

TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider)

Tenta formatar o valor da instância de número float atual para o intervalo de caracteres fornecido.

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Single)

Tenta analisar um intervalo de caracteres UTF-8 em um valor.

TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, Single)

Tenta analisar um intervalo de caracteres UTF-8 em um valor.

TryParse(ReadOnlySpan<Byte>, Single)

Tenta converter um intervalo de caracteres UTF-8 que contém a representação de cadeia de caracteres de um número em seu número de ponto flutuante de precisão simples equivalente.

TryParse(ReadOnlySpan<Char>, IFormatProvider, Single)

Tenta analisar um intervalo de caracteres em um valor.

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Single)

Converte a representação de intervalo de um número em um formato específico da cultura e um estilo especificados em seu número de ponto flutuante de precisão simples equivalente. Um valor retornado indica se a conversão foi bem-sucedida ou falhou.

TryParse(ReadOnlySpan<Char>, Single)

Converte a representação de cadeia de caracteres de um número em um intervalo de caracteres em um número de ponto flutuante de precisão simples equivalente. Um valor retornado indica se a conversão foi bem-sucedida ou falhou.

TryParse(String, IFormatProvider, Single)

Tenta analisar uma cadeia de caracteres em um valor.

TryParse(String, NumberStyles, IFormatProvider, Single)

Converte a representação de cadeia de caracteres de um número em um estilo e formato específico da cultura especificados em seu equivalente de número de ponto flutuante de precisão simples. Um valor retornado indica se a conversão foi bem-sucedida ou falhou.

TryParse(String, Single)

Converte a representação da cadeia de caracteres de um número no número de ponto flutuante de precisão simples equivalente. Um valor retornado indica se a conversão foi bem-sucedida ou falhou.

Operadores

Equality(Single, Single)

Retorna um valor que indica se os dois valores Single especificados são iguais.

GreaterThan(Single, Single)

Retorna um valor que indica se um valor Single especificado é maior que outro valor Single especificado.

GreaterThanOrEqual(Single, Single)

Retorna um valor que indica se um valor Single especificado é maior ou igual a outro valor Single especificado.

Inequality(Single, Single)

Retorna um valor que indica se os dois valores Single especificados não são iguais.

LessThan(Single, Single)

Retorna um valor que indica se um valor especificado de Single é menor que outro valor especificado de Single.

LessThanOrEqual(Single, Single)

Retorna um valor que indica se um valor Single especificado é menor ou igual a outro valor Single especificado.

Implantações explícitas de interface

IAdditionOperators<Single,Single,Single>.Addition(Single, Single)

Adiciona dois valores juntos para calcular sua soma.

IAdditiveIdentity<Single,Single>.AdditiveIdentity

Obtém a identidade aditiva do tipo atual.

IBinaryNumber<Single>.AllBitsSet

Obtém uma instância do tipo binário no qual todos os bits são definidos.

IBitwiseOperators<Single,Single,Single>.BitwiseAnd(Single, Single)

Calcula o bit a bit e de dois valores.

IBitwiseOperators<Single,Single,Single>.BitwiseOr(Single, Single)

Calcula o bit a bit ou de dois valores.

IBitwiseOperators<Single,Single,Single>.ExclusiveOr(Single, Single)

Calcula o exclusivo ou de dois valores.

IBitwiseOperators<Single,Single,Single>.OnesComplement(Single)

Calcula a representação ones-complement de um determinado valor.

IComparable.CompareTo(Object)

Compara a instância atual com outro objeto do mesmo tipo e retorna um inteiro que indica se a instância atual precede, segue ou ocorre na mesma posição da ordem de classificação do outro objeto.

IConvertible.GetTypeCode()

Retorna o TypeCode para essa instância.

IConvertible.ToBoolean(IFormatProvider)

Para obter uma descrição desse membro, confira ToBoolean(IFormatProvider).

IConvertible.ToByte(IFormatProvider)

Para obter uma descrição desse membro, confira ToByte(IFormatProvider).

IConvertible.ToChar(IFormatProvider)

Não há suporte para esta conversão. A tentativa de usar esse método lança um InvalidCastException.

IConvertible.ToDateTime(IFormatProvider)

Não há suporte para esta conversão. A tentativa de usar esse método lança um InvalidCastException.

IConvertible.ToDecimal(IFormatProvider)

Para obter uma descrição desse membro, confira ToDecimal(IFormatProvider).

IConvertible.ToDouble(IFormatProvider)

Para obter uma descrição desse membro, confira ToDouble(IFormatProvider).

IConvertible.ToInt16(IFormatProvider)

Para obter uma descrição desse membro, confira ToInt16(IFormatProvider).

IConvertible.ToInt32(IFormatProvider)

Para obter uma descrição desse membro, confira ToInt32(IFormatProvider).

IConvertible.ToInt64(IFormatProvider)

Para obter uma descrição desse membro, confira ToInt64(IFormatProvider).

IConvertible.ToSByte(IFormatProvider)

Para obter uma descrição desse membro, confira ToSByte(IFormatProvider).

IConvertible.ToSingle(IFormatProvider)

Para obter uma descrição desse membro, confira ToSingle(IFormatProvider).

IConvertible.ToType(Type, IFormatProvider)

Para obter uma descrição desse membro, confira ToType(Type, IFormatProvider).

IConvertible.ToUInt16(IFormatProvider)

Para obter uma descrição desse membro, confira ToUInt16(IFormatProvider).

IConvertible.ToUInt32(IFormatProvider)

Para obter uma descrição desse membro, confira ToUInt32(IFormatProvider).

IConvertible.ToUInt64(IFormatProvider)

Para obter uma descrição desse membro, confira ToUInt64(IFormatProvider).

IDecrementOperators<Single>.Decrement(Single)

Diminui um valor.

IDivisionOperators<Single,Single,Single>.Division(Single, Single)

Divide um valor por outro para calcular seu quociente.

IFloatingPoint<Single>.GetExponentByteCount()

Obtém o número de bytes que serão gravados como parte de TryWriteExponentLittleEndian(Span<Byte>, Int32).

IFloatingPoint<Single>.GetExponentShortestBitLength()

Obtém o comprimento, em bits, da representação complementar dos dois mais curtos do expoente atual.

IFloatingPoint<Single>.GetSignificandBitLength()

Obtém o comprimento, em bits, do significando atual.

IFloatingPoint<Single>.GetSignificandByteCount()

Obtém o número de bytes que serão gravados como parte de TryWriteSignificandLittleEndian(Span<Byte>, Int32).

IFloatingPoint<Single>.TryWriteExponentBigEndian(Span<Byte>, Int32)

Tenta gravar o expoente atual, no formato big-endian, em um determinado intervalo.

IFloatingPoint<Single>.TryWriteExponentLittleEndian(Span<Byte>, Int32)

Tenta gravar o expoente atual, no formato little-endian, em um determinado intervalo.

IFloatingPoint<Single>.TryWriteSignificandBigEndian(Span<Byte>, Int32)

Tenta gravar o significando atual, no formato big-endian, em um determinado intervalo.

IFloatingPoint<Single>.TryWriteSignificandLittleEndian(Span<Byte>, Int32)

Tenta gravar o significando atual, no formato little-endian, em um determinado intervalo.

IFloatingPointConstants<Single>.E

Obtém a constante ematemática .

IFloatingPointConstants<Single>.Pi

Obtém a constante pimatemática .

IFloatingPointConstants<Single>.Tau

Obtém a constante taumatemática .

IFloatingPointIeee754<Single>.Epsilon

Obtém o menor valor de modo que pode ser adicionado a 0 que não resulta em 0.

IFloatingPointIeee754<Single>.NaN

Obtém um valor que representa NaN.

IFloatingPointIeee754<Single>.NegativeInfinity

Obtém um valor que representa negativo infinity.

IFloatingPointIeee754<Single>.NegativeZero

Obtém um valor que representa negativo zero.

IFloatingPointIeee754<Single>.PositiveInfinity

Obtém um valor que representa positivo infinity.

IIncrementOperators<Single>.Increment(Single)

Incrementa um valor.

IMinMaxValue<Single>.MaxValue

Obtém o valor máximo do tipo atual.

IMinMaxValue<Single>.MinValue

Obtém o valor mínimo do tipo atual.

IModulusOperators<Single,Single,Single>.Modulus(Single, Single)

Divide dois valores juntos para calcular seu módulo ou resto.

IMultiplicativeIdentity<Single,Single>.MultiplicativeIdentity

Obtém a identidade multiplicativa do tipo atual.

IMultiplyOperators<Single,Single,Single>.Multiply(Single, Single)

Multiplica dois valores juntos para calcular seu produto.

INumberBase<Single>.IsCanonical(Single)

Determina se um valor está em sua representação canônica.

INumberBase<Single>.IsComplexNumber(Single)

Determina se um valor representa um número complexo.

INumberBase<Single>.IsImaginaryNumber(Single)

Determina se um valor representa um número imaginário puro.

INumberBase<Single>.IsZero(Single)

Determina se um valor é zero.

INumberBase<Single>.One

Obtém o valor 1 do tipo.

INumberBase<Single>.Radix

Obtém a base para o tipo.

INumberBase<Single>.TryConvertFromChecked<TOther>(TOther, Single)

Representa um número de ponto flutuante de precisão simples.

INumberBase<Single>.TryConvertFromSaturating<TOther>(TOther, Single)

Representa um número de ponto flutuante de precisão simples.

INumberBase<Single>.TryConvertFromTruncating<TOther>(TOther, Single)

Representa um número de ponto flutuante de precisão simples.

INumberBase<Single>.TryConvertToChecked<TOther>(Single, TOther)

Tenta converter uma instância do tipo atual em outro tipo, gerando uma exceção de estouro para todos os valores que ficam fora do intervalo representável do tipo atual.

INumberBase<Single>.TryConvertToSaturating<TOther>(Single, TOther)

Tenta converter uma instância do tipo atual em outro tipo, saturando todos os valores que ficam fora do intervalo representável do tipo atual.

INumberBase<Single>.TryConvertToTruncating<TOther>(Single, TOther)

Tenta converter uma instância do tipo atual em outro tipo, truncando todos os valores que estão fora do intervalo representável do tipo atual.

INumberBase<Single>.Zero

Obtém o valor 0 do tipo.

ISignedNumber<Single>.NegativeOne

Obtém o valor -1 do tipo.

ISubtractionOperators<Single,Single,Single>.Subtraction(Single, Single)

Subtrai dois valores para calcular sua diferença.

IUnaryNegationOperators<Single,Single>.UnaryNegation(Single)

Calcula a negação unária de um valor.

IUnaryPlusOperators<Single,Single>.UnaryPlus(Single)

Calcula a mais unária de um valor.

Aplica-se a

Acesso thread-safe

Todos os membros desse tipo são thread-safe. Os membros que aparentam modificar efetivamente o estado retornam uma nova instância inicializada com o novo valor. Assim como acontece com qualquer outro tipo, a leitura e a gravação em uma variável compartilhada que contém uma instância desse tipo devem ser protegidas por um bloqueio para garantir thread-safe.

Confira também