Single 结构

定义

表示单精度浮点数。

public value class float : IComparable, IComparable<float>, IConvertible, IEquatable<float>, IFormattable
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, 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, 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<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 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>
[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 IFormattable
    interface IParsable<single>
    interface ISpanFormattable
    interface ISpanParsable<single>
    interface IUtf8SpanFormattable
    interface IUtf8SpanParsable<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 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 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, 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 IComparable, IConvertible, IFormattable
Public Structure Single
Implements IComparable, IComparable(Of Single), IEquatable(Of Single), IFormattable
继承
Single
属性
实现
IComparable IComparable<Single> IConvertible IEquatable<Single> IFormattable IComparable<TSelf> IEquatable<TSelf> IParsable<Single> IParsable<TSelf> ISpanFormattable ISpanParsable<Single> ISpanParsable<TSelf> IUtf8SpanFormattable IUtf8SpanParsable<Single> IUtf8SpanParsable<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>

注解

Single 值类型表示一个单精度 32 位数字,其值的范围介于负 3.402823e38 到正 3.402823e38 之间,且可为正零或负零、PositiveInfinityNegativeInfinity,但不是一个数字 (NaN)。 它旨在表示非常大(例如行星或星系之间的距离)或极小的值(例如物质的分子量(以千克为单位)),且通常不精确(例如从地球到另一个太阳系的距离)。 Single 类型符合针对二进制浮点运算的 IEC 60559:1989 (IEEE 754) 标准。

System.Single 提供了用于比较此类型的实例、将实例的值转换为其字符串表示形式以及将数字的字符串表示形式转换为此类型的实例的相应方法。 有关格式规范代码如何控制值类型的字符串表示形式的信息,请参阅格式设置类型标准数字格式字符串自定义数字格式字符串

浮点表示形式和精度

Single 数据类型能以 32 位二进制格式存储单精度浮点值,如下表所示:

部件 比特
有效数或尾数 0-22
Exponent 23-30
符号(0 = 正,1 = 负) 31

正如十进制小数无法精确表示某些小数值(如 1/3 或 Math.PI),二进制小数也无法表示某些小数值。 例如,2/10 可用 .2 精确表示为一个十进制小数,用 .0011111001001100 表示为一个二进制小数,并采用会重复到无穷大的“1100”模式。 在此情况下,浮点值提供了它所表示的数字的非精确表示形式。 对原始浮点值执行其他数学运算通常会加剧导致其精度不足。 例如,如果将 .3 乘以 10 与将 .3 与 .3 相加 9 次的结果进行比较,您会发现加法产生的结果不太精确,因为它涉及的运算比乘法多了 8 次。 请注意,仅当使用“R”Single来显示两个 值时,此差异才会明显;如有必要,则会显示 Single 类型支持的全部 9 位精度。

using System;

public class Example12
{
    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:           {result1:R}");
        Console.WriteLine($".2 Added 10 times: {result2:R}");
    }
}
// The example displays the following output:
//       .2 * 10:           2
//       .2 Added 10 times: 2.0000002
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 Example13
    Public Sub Main()
        Dim value As Single = 0.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.0000002

由于某些数字无法完全表示为小数二进制值,因此浮点数只能近似于实数。

所有浮点数的有效位数均有限,而这也决定了浮点值近似实数的精度。 Single 值的精度最高为 7 位十进制,但内部最多可保持 9 位。 这意味着某些浮点运算可能缺乏用于更改浮点值的精度。 以下示例定义了一个较大的单精度浮点数值,然后将 Single.Epsilon 与一千万亿的乘积添加到其中。 但是,其乘积太小,因而无法修改原始浮点值。 其最低有效位为千分之一,而乘积中最高有效位为 10-30

using System;

public class Example13
{
    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

浮点数的有限精度会产生以下几种后果:

  • 对于特定精度而言显得相等的两个浮点数可能比较不相等,因为它们的最低有效位不同。 在以下示例中,会将一系列数字相加,并将它们的总数与预期的总数进行比较。 对 Equals 方法的调用指示值不相等。

    using System;
    
    public class PrecisionList3Example
    {
        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 ({total}) does not equal the total ({result}).");
        }
    }
    
    // The example displays the following output on .NET:
    //      The sum of the values (27.650002) does not equal the total (27.65).
    // The example displays the following output on .NET Framework:
    //      The sum of the values (27.65) 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).
    
        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 ({total}) does not equal the total ({result}).")
        End If
    End Sub
    
    ' The example displays the following output on .NET:
    '      The sum of the values (27.650002) does not equal the total (27.65).
    ' The example displays the following output on .NET Framework:
    '      The sum of the values (27.65) does not equal the total (27.65).
    

    由于加法运算期间精度损失,这两个值不相等。 在此情况下,可通过调用 Math.Round(Double, Int32) 方法在执行比较之前将 Single 值舍入为所需的精度来解决此问题。

  • 如果使用十进制数,则使用浮点数的数学运算或比较运算可能不会产生相同的结果,因为二进制浮点数可能不等于十进制数。 上一示例通过显示将 .3 乘以 10 并将 .3 加到 .3 一共 9 次的结果来说明这一点。

    当使用小数值的数值运算的准确性十分重要时,请使用 Decimal 类型而不是 Single 类型。 当使用超过 Int64UInt64 类型范围的整数值的数值运算的精度十分重要时,请使用 BigInteger 类型。

  • Single 值的精度低于 Double 值。 由于精度差异,转换为看似等效的 SingleDouble 值通常不等于 Double 值。 在以下示例中,相同除法运算的结果会赋给 Double 值和 Single 值。 将 Single 值强制转换为 Double 后,两个值的比较表明它们不相等。

    using System;
    
    public class Example9
    {
        public static void Run()
        {
            double value1 = 1 / 3.0;
            float sValue2 = 1 / 3.0f;
            double value2 = (double)sValue2;
            Console.WriteLine($"{value1:R} = {value2:R}: {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 Example10
        Public Sub Run()
            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
    

    要避免此问题,请使用 Double 数据类型代替 Single 数据类型,或使用 Round 方法以使两个值具有相同的精度。

相等性测试

要被视为相等,两个 Single 值必须表示相同的值。 但是,由于值之间的精度差异,或是因为一个或两个值的精度损失,本应相同的浮点值通常会由于最低有效位数的差异而变得不相等。 因此,调用 Equals 方法来确定两个值是否相等,或调用 CompareTo 方法来确定两个 Single 值之间的关系,通常会产生意外的结果。 此问题在以下示例中十分明显;其中,两个明显相等的 Single 值的结果并不相等,因为第一个值的精度为 7 位,而第二个值的精度为 9 位。

using System;

public class Example
{
   public static void Main()
   {
      float value1 = .3333333f;
      float value2 = 1.0f/3;
      Console.WriteLine($"{value1:R} = {value2:R}: {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 Example1
    Public Sub Main()
        Dim value1 As Single = 0.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

遵循不同代码路径并以不同方式进行操作的计算所得值通常被证明是不相等的。 在以下示例中,会将一个 Single 值取平方,然后计算平方根以恢复原始值。 第二个 Single 会先乘以 3.51 并平方,再对结果开平方根,最后除以 3.51 来还原原始值。 虽然这两个值看起来相同,但调用 Equals(Single) 方法却表明它们并不相等。

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($"{value1} = {value2}: {value1.Equals(value2)}");

// The example displays the following output on .NET:
//       10.201438 = 10.201439: False
// The example displays the following output on .NET Framework:
//       10.20144 = 10.20144: False
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
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))

' The example displays the following output on .NET:
'       10.201438 = 10.201439: False
' The example displays the following output on .NET Framework:
'       10.20144 = 10.20144: False

如果精度损失可能会影响比较结果,则可使用以下方法,而不是调用 EqualsCompareTo 方法:

  • 调用 Math.Round 方法以确保两个值具有相同的精度。 以下示例修改了前一示例以使用此方法,以使两个小数值等效。

    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($"{value1:R} = {value2:R}: {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 Example3
        Public Sub Main()
            Dim value1 As Single = 0.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
    

    精度问题仍适用于中点值的舍入。 有关更多信息,请参见 Math.Round(Double, Int32, MidpointRounding) 方法。

  • 测试近似相等性,而不是相等性。 此方法要求定义一个两个值可以相差但仍然相等的绝对量,或是定义一个较小值与较大值可以相差的相对量。

    Warning

    Single.Epsilon 有时会在测试相等性时用作两个 Single 值之间差异的绝对度量结果。 但是,Single.Epsilon 测量的是可以在值为零的 Single 中加上或减去的最小可能值。 对于大多数正与负 Single 值,Single.Epsilon 的值太小,因而无法检测到。 因此,除零值外,我们不建议将其用于相等性测试。

    以下示例使用后一种方法来定义 IsApproximatelyEqual 方法,而该方法可用于测试两个值之间的相对差值。 它还对比了对 IsApproximatelyEqual 方法和 Equals(Single) 方法的调用结果。

    public static void Main()
    {
        float one1 = .1f * 10;
        float one2 = 0f;
        for (int ctr = 1; ctr <= 10; ctr++)
            one2 += .1f;
    
        Console.WriteLine($"{one1:R} = {one2:R}: {one1.Equals(one2)}");
        Console.WriteLine($"{one1:R} is approximately equal to {one2:R}: " +
            $"{IsApproximatelyEqual(one1, one2, .000001f)}");
    
        float negativeOne1 = -1 * one1;
        float negativeOne2 = -1 * one2;
    
        Console.WriteLine($"{negativeOne1:R} = {negativeOne2:R}: {negativeOne1.Equals(negativeOne2)}");
        Console.WriteLine($"{negativeOne1:R} is approximately equal to {negativeOne2:R}: " +
            $"{IsApproximatelyEqual(negativeOne1, negativeOne2, .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 on .NET:
    //       1 = 1.0000001: False
    //       1 is approximately equal to 1.0000001: True
    //       -1 = -1.0000001: False
    //       -1 is approximately equal to -1.0000001: 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
    
    Public Sub Main()
        Dim one1 As Single = 0.1 * 10
        Dim one2 As Single = 0
        For ctr As Integer = 1 To 10
            one2 += CSng(0.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, 0.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)
        ElseIf Single.IsInfinity(value2) Or Single.IsNaN(value2) Then
            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
    
    ' The example displays the following output:
    '       1 = 1.0000001: False
    '       1 is approximately equal to 1.0000001: True
    

浮点值和异常

与具有整型类型的运算不同,具有浮点型的运算不会引发异常,而后者在非法运算(如除以零或溢出)的情况下会引发异常。 相反,在这些情况下,浮点运算的结果为零、正无穷大、负无穷大或不是数字 (NaN):

  • 如果浮点运算的结果对于目标格式来说太小,则结果为零。 当两个非常小的浮点数相乘时,可能会出现此情况,如以下示例所示。

    float value1 = 1.163287e-36f;
    float value2 = 9.164234e-25f;
    float result = value1 * value2;
    Console.WriteLine($"{value1} * {value2} = {result}");
    Console.WriteLine($"{result} = 0: {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 Example7
        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
    
  • 如果浮点运算的结果大小超出目标格式的范围,则运算结果为 PositiveInfinityNegativeInfinity,具体取决于结果的符号。 导致 Single.MaxValue 溢出的运算的结果为 PositiveInfinity,而导致 Single.MinValue 溢出的运算的结果为 NegativeInfinity,如以下示例所示。

    float value1 = 3.065e35f;
    float value2 = 6.9375e32f;
    float result = value1 * value2;
    Console.WriteLine($"PositiveInfinity: {Single.IsPositiveInfinity(result)}");
    Console.WriteLine($"NegativeInfinity: {Single.IsNegativeInfinity(result)}");
    Console.WriteLine();
    
    value1 = -value1;
    result = value1 * value2;
    Console.WriteLine($"PositiveInfinity: {Single.IsPositiveInfinity(result)}");
    Console.WriteLine($"NegativeInfinity: {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 Example8
        Public Sub Main()
            Dim value1 As Single = 3.065E+35
            Dim value2 As Single = 6.9375E+32
            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 也源于将正被除数除以零,而 NegativeInfinity 源于将负被除数除以零。

  • 如果浮点运算无效,则运算结果为 NaN。 例如,NaN 源自以下运算:

    • 除以零,且被除数为零。 请注意,除以零的其他情况会导致 PositiveInfinityNegativeInfinity
    • 具有无效输入的任意浮点运算。 例如,尝试查找负值的平方根会返回 NaN
    • 参数值为 Single.NaN 的任意运算。

类型转换

Single 结果未定义任何显式或隐式转换运算符;相反,转换会由编译器实现。

下表列出了其他基元数值类型的值可能转换为 Single 值。 它还指示转换是扩大还是缩小,以及生成的 Single 精度是否可能小于原始值。

扩大/收缩 潜在精度损失
Byte 扩大
Decimal 扩大

请注意,C# 需使用强制转换运算符。
是的。 Decimal 支持 29 位十进制数字的精度,而 Single 支持 9 位。
Double 缩小;超出范围的值将转换为 Double.NegativeInfinityDouble.PositiveInfinity 是的。 Double 支持 17 位十进制数字的精度,而 Single 支持 9 位。
Int16 扩大
Int32 扩大 是的。 Int32 支持 10 位十进制数字的精度,而 Single 支持 9 位。
Int64 扩大 是的。 Int64 支持 19 位十进制数字的精度,而 Single 支持 9 位。
SByte 扩大
UInt16 扩大
UInt32 扩大 是的。 UInt32 支持 10 位十进制数字的精度,而 Single 支持 9 位。
UInt64 扩大 是的。 Int64 支持 20 位十进制数字的精度,而 Single 支持 9 位。

以下示例会将其他基元数值类型的最小值或最大值转换为 Single 值。

using System;

public class Example4
{
    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($"{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)
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 Example5
    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)

此外,DoubleDouble.NaNDouble.PositiveInfinityDouble.NegativeInfinity 将分别转换为 Single.NaNSingle.PositiveInfinitySingle.NegativeInfinity

请注意,将某些数值类型的值转换为 Single 值可能涉及精度损失。 如示例所示,将 DecimalDoubleInt32Int64UInt32UInt64 值转换为 Single 值时,可能会丢失精度。

Single 值转换为 Double 值是一种扩大转换。 如果Double 类型没有 Single 值的精确表示形式,则转换可能会导致精度损失。

Single 值转换为除 Double 之外的任何基元数值数据类型的值的操作均属于收缩转换,且需在 C# 中使用强制转换运算符或在 Visual Basic 中使用转换方法。 超出目标数据类型范围的值(由目标类型的 MinValueMaxValue 属性进行定义)的行为如下表所示。

目标类型 Result
任何整型 如果在 checked 上下文中进行转换,则会引发 OverflowException 异常。

如果转换发生在未选中的上下文(C# 中的默认值)中,则此转换运算会成功,但值会溢出。
Decimal 异常 OverflowException

此外,在 checked 上下文中转换为整数时,Single.NaNSingle.PositiveInfinitySingle.NegativeInfinity 会引发 OverflowException,但在 unchecked 上下文中转换为整数时,这些值会溢出。 对于转换为 Decimal,它们始终会引发 OverflowException。 对于向 Double 进行转换,它们会分别转换为 Double.NaNDouble.PositiveInfinityDouble.NegativeInfinity

请注意,将 Single 值转换为其他数值类型可能会导致精度损失。 如果要转换非整型 Single 值,如示例输出所示,将 Single 值舍入(如在 Visual Basic 中)或截断(如在 C# 和 F# 中)时,会丢失小数部分。 对于向 Decimal 值进行转换,Single 值在目标数据类型中可能没有精确的表示形式。

以下示例会将多个 Single 值转换为其他几种数字类型。 在 Visual Basic(默认)、C#(由于 checked 关键字)和 F#(由于 open Checked 语句)中,将在 checked 上下文中执行转换。 该示例的输出显示了在 checked 和 unchecked 上下文中转换的结果。 可以在未选中上下文中执行转换:在 Visual Basic 中,通过编译时使用 /removeintchecks+ 编译器开关;在 C# 中,通过注释掉 checked 语句;在 F# 中,通过注释掉 open Checked 语句。

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($"{value} ({value.GetType().Name}) --> {lValue} (0x{lValue:X16}) ({lValue.GetType().Name})");
        }
        catch (OverflowException)
        {
            Console.WriteLine($"Unable to convert {value} to Int64.");
        }
        try
        {
            UInt64 ulValue = (ulong)value;
            Console.WriteLine($"{value} ({value.GetType().Name}) --> {ulValue} (0x{ulValue:X16}) ({ulValue.GetType().Name})");
        }
        catch (OverflowException)
        {
            Console.WriteLine($"Unable to convert {value} to UInt64.");
        }
        try
        {
            Decimal dValue = (decimal)value;
            Console.WriteLine($"{value} ({value.GetType().Name}) --> {dValue} ({dValue.GetType().Name})");
        }
        catch (OverflowException)
        {
            Console.WriteLine($"Unable to convert {value} to Decimal.");
        }

        Double dblValue = value;
        Console.WriteLine($"{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 ∞ to Int64.
//       Unable to convert ∞ to UInt64.
//       Unable to convert ∞ to Decimal.
//       ∞ (Single) --> ∞ (Double)
//
//       Unable to convert -∞ to Int64.
//       Unable to convert -∞ to UInt64.
//       Unable to convert -∞ to Decimal.
//       -∞ (Single) --> -∞ (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 Example6
    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 ∞ to Int64.
'       Unable to convert ∞ to UInt64.
'       Unable to convert ∞ to Decimal.
'       ∞ (Single) --> ∞ (Double)
'
'       Unable to convert -∞ to Int64.
'       Unable to convert -∞ to UInt64.
'       Unable to convert -∞ to Decimal.
'       -∞ (Single) --> -∞ (Double)

有关数值类型转换的详细信息,请参阅 .NET 中的 Type ConversionType Conversion Tables

浮点功能

Single 结构和相关类型提供了执行以下类别的运算的方法:

  • 值的比较。 你可调用 Equals 方法来确定两个 Single 值是否相等,也可调用 CompareTo 方法来确定两个值之间的关系。

    Single 结构还支持一整套比较运算符。 例如,可测试相等或不相等,或者确定一个值是大于还是等于另一个值。 如果其中一个操作数是 Double,则在执行比较之前,Single 值将转换为 Double。 如果其中一个操作数是整型,则在执行比较之前会将其转换为 Single。 尽管这些运算属于扩大转换,但它们可能涉及精度损失。

    Warning

    由于精度差异,你期望相等的两个 Single 值可能会变得不相等,而这会影响比较结果。 有关比较两个 值的更多信息,请参阅Single部分。

    此外,还可调用 IsNaNIsInfinityIsPositiveInfinityIsNegativeInfinity 方法来针对这些特殊值进行测试。

  • 数学运算。 常见的算术运算(如加、减、乘和除)将由语言编译器和公共中间语言 (CIL) 指令实现,而不是由 Single 方法实现。 如果数学运算中的另一个操作数是 Double,则在执行运算之前,Single 会转换为 Double,而运算结果也是 Double 值。 如果另一个操作数是整型,则在执行作之前将其转换为 Single,而运算结果也是 Single 值。

    可通过调用 static 类中的 Shared(在 Visual Basic 中为 System.Math)方法来执行其他数学运算。 这些方法包括通常用于算术(如 Math.AbsMath.SignMath.Sqrt)、几何(如 Math.CosMath.Sin)以及微积分(如 Math.Log)的其他方法。 在所有情况下,Single 值均会转换为 Double

    还可操控 Single 值中的各个位。 BitConverter.GetBytes(Single) 方法会在字节数组中返回其位模式。 通过将该字节数组传递给 BitConverter.ToInt32 方法,还可将 Single 值的位模式保留为 32 位整数。

  • 舍入。 舍入技术通常会用作减少因浮点表示和精度问题所导致的值差异影响。 可以调用 Single 方法来舍入 Math.Round 值。 但是,请注意,在调用此方法之前,Single 值会转换为 Double,且此转换可能会涉及精度损失。

  • 格式设置。 可通过调用 Single 方法或使用ToString功能,将 值转换为其字符串表示形式。 有关格式字符串如何控制浮点值的字符串表示形式的信息,请参阅标准数值格式字符串自定义数字格式字符串

  • 分析字符串。 可通过调用 SingleParse 方法将浮点值的字符串表示形式转换为 TryParse 值。 如果分析操作失败,Parse 方法则会引发异常,而 TryParse 方法会返回 false

  • 类型转换Single 结构为 IConvertible 接口提供显式接口实现,该接口支持在任意两种标准.NET数据类型之间进行转换。 语言编译器还支持所有其他标准数值类型的值的隐式转换,但从 DoubleSingle 值的转换除外。 将除 Double 之外的任意标准数值类型的值转换为 Single 均属于扩大转换,且无需使用强制转换运算符或转换方法。

    但是,32 位与 64 位整数值的转换可能涉及精度损失。 下表列出了 32 位、64 位与 Double 类型之间的精度差异:

    类型 最大精度(十进制数字) 内部精度(十进制数字)
    Double 15 17
    Int32UInt32 10 10
    Int64UInt64 19 19
    Single 7 9

    精度问题最常影响被转换为 Single 值的 Double 值。 在以下示例中,相同的除法运算生成的两个值不相等,因为其中一个值是转换为 Double 的单精度浮点值。

    Double value1 = 1 / 3.0;
    Single sValue2 = 1 / 3.0f;
    Double value2 = (Double)sValue2;
    Console.WriteLine($"{value1:R} = {value2:R}: {value1.Equals(value2)}");
    
    // The example displays the following output on .NET:
    //        0.3333333333333333 = 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
    
    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))
    
    ' The example displays the following output:
    '       0.3333333333333333 = 0.3333333432674408: False
    

字段

名称 说明
E

表示由常量指定的自然对数基数,e.

Epsilon

表示大于零的最小正 Single 值。 此字段为常量。

MaxValue

表示最大可能值 Single。 此字段为常量。

MinValue

表示可能的最小值 Single。 此字段为常量。

NaN

表示数字(NaN)。 此字段为常量。

NegativeInfinity

表示负无穷大。 此字段为常量。

NegativeZero

表示负零(-0)。

Pi

表示圆的周长与其直径的比率,由常量指定,π。

PositiveInfinity

表示正无穷大。 此字段为常量。

Tau

表示一个轮次的弧度数,由常量 τ 指定。

方法

名称 说明
Abs(Single)

计算值的绝对值。

Acos(Single)

计算值的反余弦值。

Acosh(Single)

计算值的双曲反余弦值。

AcosPi(Single)

计算值的反余弦值,并将结果除以 pi

Asin(Single)

计算值的反正弦值。

Asinh(Single)

计算值的双曲反正弦值。

AsinPi(Single)

计算值的反正弦值,并将结果除以 pi

Atan(Single)

计算值的反正切值。

Atan2(Single, Single)

计算两个值的商的反正切值。

Atan2Pi(Single, Single)

计算两个值的商的反正切值,并将结果除以 pi

Atanh(Single)

计算值的双曲反正切值。

AtanPi(Single)

计算值的反正切值,并将结果除以 pi。

BitDecrement(Single)

返回与指定值进行比较的最大值。

BitIncrement(Single)

返回与指定值进行比较的最小值。

Cbrt(Single)

计算值的多维数据集根。

Ceiling(Single)

计算值的上限。

Clamp(Single, Single, Single)

将值固定到非独占最小值和最大值。

ClampNative(Single, Single, Single)

使用特定于平台的行为NaNNegativeZero,将值固定到非独占的最小值和最大值。

CompareTo(Object)

将此实例与指定的对象进行比较,并返回一个整数,该整数指示此实例的值是小于、等于还是大于指定对象的值。

CompareTo(Single)

将此实例与指定的单精度浮点数进行比较,并返回一个整数,该值指示此实例的值是小于、等于还是大于指定的单精度浮点数的值。

ConvertToInteger<TInteger>(Single)

使用溢出时饱和度将值转换为指定的整数类型

ConvertToIntegerNative<TInteger>(Single)

使用特定于平台的行为在溢出时将值转换为指定的整数类型。

CopySign(Single, Single)

将值的符号复制到另一个值的符号。

Cos(Single)

计算值的余弦值。

Cosh(Single)

计算值的双曲余弦值。

CosPi(Single)

计算已由 pi其乘数的值的余弦值。

CreateChecked<TOther>(TOther)

从值创建当前类型的实例,为超出当前类型的可表示范围的任何值引发溢出异常。

CreateSaturating<TOther>(TOther)

从值创建当前类型的实例,使属于当前类型的可表示范围之外的任何值饱和。

CreateTruncating<TOther>(TOther)

从值创建当前类型的实例,截断属于当前类型的可表示范围之外的任何值。

DegreesToRadians(Single)

将给定值从度转换为弧度。

Equals(Object)

返回一个值,该值指示此实例是否等于指定的对象。

Equals(Single)

返回一个值,该值指示此实例和指定的 Single 对象是否表示相同的值。

Exp(Single)

E计算提升到给定功率。

Exp10(Single)

10计算提升到给定功率。

Exp10M1(Single)

10计算提升到给定的幂并减去一个。

Exp2(Single)

2计算提升到给定功率。

Exp2M1(Single)

2计算提升到给定的幂并减去一个。

ExpM1(Single)

E计算提升到给定的幂并减去一个。

Floor(Single)

计算值的下限。

FusedMultiplyAdd(Single, Single, Single)

计算三个值的融合乘法。

GetHashCode()

返回此实例的哈希代码。

GetTypeCode()

返回 TypeCode 值类型的 Single值 。

Hypot(Single, Single)

计算给定的两个值,该值表示右角三角形中较短边的长度。

Ieee754Remainder(Single, Single)

计算 IEEE 754 指定的两个值的余数。

ILogB(Single)

计算值的整数对数。

IsEvenInteger(Single)

确定值是否表示偶数。

IsFinite(Single)

确定指定的值是有限值(零、非正常值还是正常值)。

IsInfinity(Single)

返回一个值,该值指示指定的数字的计算结果为负数还是正无穷大。

IsInteger(Single)

确定值是否表示整型值。

IsNaN(Single)

返回一个值,该值指示指定的值是否不是数字(NaN)。

IsNegative(Single)

确定指定的值是否为负值。

IsNegativeInfinity(Single)

返回一个值,该值指示指定的数字是否计算为负无穷大。

IsNormal(Single)

确定指定的值是否正常。

IsOddInteger(Single)

确定值是否表示奇数整数。

IsPositive(Single)

确定值是否为正值。

IsPositiveInfinity(Single)

返回一个值,该值指示指定的数字是否计算为正无穷大。

IsPow2(Single)

确定值是否为 2 的幂。

IsRealNumber(Single)

确定值是否表示实数。

IsSubnormal(Single)

确定指定的值是否为非正常值。

Lerp(Single, Single, Single)

根据给定权重在两个值之间执行线性内插。

Log(Single, Single)

计算指定基中的值的对数。

Log(Single)

计算值的自然(base-E 对数)。

Log10(Single)

计算值的 base-10 对数。

Log10P1(Single)

计算值加 10 的 base-10 对数。

Log2(Single)

计算值的 log2。

Log2P1(Single)

计算值加 1 的 base-2 对数。

LogP1(Single)

计算值加 1 的自然(base-E) 对数。

Max(Single, Single)

比较两个值与计算值更大。

MaxMagnitude(Single, Single)

比较两个值与计算值更大。

MaxMagnitudeNumber(Single, Single)

将两个值与计算进行比较,如果输入 NaN是,则返回另一个值。

MaxNative(Single, Single)

比较两个值与使用特定于平台的行为 NaNNegativeZero更大的计算值。

MaxNumber(Single, Single)

将两个值与计算进行比较,如果输入 NaN是,则返回另一个值。

Min(Single, Single)

比较两个值与计算值较小。

MinMagnitude(Single, Single)

比较两个值与计算值较小。

MinMagnitudeNumber(Single, Single)

将两个值与计算进行比较,如果输入 NaN是,则返回另一个值。

MinNative(Single, Single)

将两个值与计算进行比较,后者使用特定于平台的行为 NaNNegativeZero

MinNumber(Single, Single)

将两个值与计算进行比较,如果输入 NaN较小,则返回另一个值。

MultiplyAddEstimate(Single, Single, Single)

计算估计值 (left * right) + 。 addend

Parse(ReadOnlySpan<Byte>, IFormatProvider)

将 UTF-8 字符的范围分析为值。

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

将 UTF-8 字符的范围分析为值。

Parse(ReadOnlySpan<Char>, IFormatProvider)

将字符的范围分析为值。

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

将包含指定样式和区域性特定格式的数字的字符串表示形式的字符范围转换为其等效的单精度浮点数。

Parse(String, IFormatProvider)

将指定区域性特定格式的数字的字符串表示形式转换为其等效的单精度浮点数。

Parse(String, NumberStyles, IFormatProvider)

将指定样式和区域性特定格式的数字的字符串表示形式转换为其等效的单精度浮点数。

Parse(String, NumberStyles)

将指定样式中的数字的字符串表示形式转换为其等效的单精度浮点数。

Parse(String)

将数字的字符串表示形式转换为其等效的单精度浮点数。

Pow(Single, Single)

计算提升到给定功率的值。

RadiansToDegrees(Single)

将给定值从弧度转换为度。

ReciprocalEstimate(Single)

计算值的对等值的估计值。

ReciprocalSqrtEstimate(Single)

计算值的倒数平方根的估计值。

RootN(Single, Int32)

计算值的第 n 个根。

Round(Single, Int32, MidpointRounding)

使用默认舍入模式将值舍入为指定数量的小数位数(ToEven)。

Round(Single, Int32)

使用默认舍入模式将值舍入为指定数量的小数位数(ToEven)。

Round(Single, MidpointRounding)

使用指定的舍入模式将值舍入到最接近的整数。

Round(Single)

使用默认舍入模式将值舍入到最接近的整数(ToEven)。

ScaleB(Single, Int32)

计算一个值及其基弧度升至指定功率的乘积。

Sign(Single)

计算值的符号。

Sin(Single)

计算值的正弦值。

SinCos(Single)

计算值的正弦值和余弦值。

SinCosPi(Single)

计算值的正弦值和余弦值。

Sinh(Single)

计算值的双曲正弦值。

SinPi(Single)

计算乘以 pi的值的正弦值。

Sqrt(Single)

计算值的平方根。

Tan(Single)

计算值的正切值。

Tanh(Single)

计算值的双曲正切值。

TanPi(Single)

计算已由 pi其乘数的值的正切值。

ToString()

将此实例的数值转换为其等效的字符串表示形式。

ToString(IFormatProvider)

使用指定的区域性特定格式信息将此实例的数值转换为其等效的字符串表示形式。

ToString(String, IFormatProvider)

使用指定的格式和区域性特定的格式信息将此实例的数值转换为其等效的字符串表示形式。

ToString(String)

使用指定的格式将此实例的数值转换为其等效的字符串表示形式。

Truncate(Single)

截断值。

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

尝试将当前实例的值格式化为 UTF-8,并将其设置为提供的字节范围。

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

尝试将当前浮点数实例的值格式化为提供的字符范围。

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Single)

尝试将 UTF-8 字符的范围分析为值。

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

尝试将 UTF-8 字符的范围分析为值。

TryParse(ReadOnlySpan<Byte>, Single)

尝试将包含数字字符串表示形式的 UTF-8 字符范围转换为其等效的单精度浮点数。

TryParse(ReadOnlySpan<Char>, IFormatProvider, Single)

尝试将字符范围分析为值。

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

将指定样式和区域性特定格式的数字的跨度表示形式转换为其等效的单精度浮点数。 返回值指示转换是成功还是失败。

TryParse(ReadOnlySpan<Char>, Single)

将字符范围中数字的字符串表示形式转换为其等效的单精度浮点数。 返回值指示转换是成功还是失败。

TryParse(String, IFormatProvider, Single)

尝试将字符串分析为值。

TryParse(String, NumberStyles, IFormatProvider, Single)

将指定样式和区域性特定格式的数字的字符串表示形式转换为其等效的单精度浮点数。 返回值指示转换是成功还是失败。

TryParse(String, Single)

将数字的字符串表示形式转换为其等效的单精度浮点数。 返回值指示转换是成功还是失败。

运营商

名称 说明
Equality(Single, Single)

返回一个值,该值指示两个指定 Single 值是否相等。

GreaterThan(Single, Single)

返回一个值,该值指示指定的 Single 值是否大于另一个指定 Single 值。

GreaterThanOrEqual(Single, Single)

返回一个值,该值指示指定的 Single 值是否大于或等于另一个指定 Single 值。

Inequality(Single, Single)

返回一个值,该值指示两个指定的 Single 值是否不相等。

LessThan(Single, Single)

返回一个值,该值指示指定的 Single 值是否小于另一个指定 Single 值。

LessThanOrEqual(Single, Single)

返回一个值,该值指示指定的 Single 值是否小于或等于另一个指定 Single 值。

显式接口实现

名称 说明
IAdditionOperators<Single,Single,Single>.Addition(Single, Single)

将两个值相加以计算其总和。

IAdditiveIdentity<Single,Single>.AdditiveIdentity

获取当前类型的累加标识。

IBinaryNumber<Single>.AllBitsSet

获取在其中设置所有位的二进制类型的实例。

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

计算两个值的按位和两个值。

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

计算两个值的按位或两个值。

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

计算独占值或两个值。

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

计算给定值的补补表示形式。

IComparable.CompareTo(Object)

将当前实例与同一类型的另一个对象进行比较,并返回一个整数,该整数指示当前实例在排序顺序中是位于排序顺序中的同一位置、之后还是位于同一位置。

IConvertible.GetTypeCode()

返回 TypeCode 此实例。

IConvertible.ToBoolean(IFormatProvider)

有关此成员的说明,请参阅 ToBoolean(IFormatProvider)

IConvertible.ToByte(IFormatProvider)

有关此成员的说明,请参阅 ToByte(IFormatProvider)

IConvertible.ToChar(IFormatProvider)

不支持此转换。 尝试使用此方法会引发一个 InvalidCastException

IConvertible.ToDateTime(IFormatProvider)

不支持此转换。 尝试使用此方法会引发一个 InvalidCastException

IConvertible.ToDecimal(IFormatProvider)

有关此成员的说明,请参阅 ToDecimal(IFormatProvider)

IConvertible.ToDouble(IFormatProvider)

有关此成员的说明,请参阅 ToDouble(IFormatProvider)

IConvertible.ToInt16(IFormatProvider)

有关此成员的说明,请参阅 ToInt16(IFormatProvider)

IConvertible.ToInt32(IFormatProvider)

有关此成员的说明,请参阅 ToInt32(IFormatProvider)

IConvertible.ToInt64(IFormatProvider)

有关此成员的说明,请参阅 ToInt64(IFormatProvider)

IConvertible.ToSByte(IFormatProvider)

有关此成员的说明,请参阅 ToSByte(IFormatProvider)

IConvertible.ToSingle(IFormatProvider)

有关此成员的说明,请参阅 ToSingle(IFormatProvider)

IConvertible.ToType(Type, IFormatProvider)

有关此成员的说明,请参阅 ToType(Type, IFormatProvider)

IConvertible.ToUInt16(IFormatProvider)

有关此成员的说明,请参阅 ToUInt16(IFormatProvider)

IConvertible.ToUInt32(IFormatProvider)

有关此成员的说明,请参阅 ToUInt32(IFormatProvider)

IConvertible.ToUInt64(IFormatProvider)

有关此成员的说明,请参阅 ToUInt64(IFormatProvider)

IDecrementOperators<Single>.Decrement(Single)

递减值。

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

将一个值除以计算其商。

IFloatingPoint<Single>.GetExponentByteCount()

获取将作为其一部分 TryWriteExponentLittleEndian(Span<Byte>, Int32)写入的字节数。

IFloatingPoint<Single>.GetExponentShortestBitLength()

获取最短两个指数的补数表示形式的长度(以位为单位)。

IFloatingPoint<Single>.GetSignificandBitLength()

获取当前标志的长度(以位为单位)。

IFloatingPoint<Single>.GetSignificandByteCount()

获取将作为其一部分 TryWriteSignificandLittleEndian(Span<Byte>, Int32)写入的字节数。

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

尝试将当前指数(采用 big-endian 格式)写入给定范围。

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

尝试将当前指数(以小端格式)写入给定范围。

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

尝试将当前符号(采用 big-endian 格式)写入给定范围。

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

尝试将当前符号(以小端格式)写入给定范围。

IFloatingPointConstants<Single>.E

获取数学常量 e

IFloatingPointConstants<Single>.Pi

获取数学常量 pi

IFloatingPointConstants<Single>.Tau

获取数学常量 tau

IFloatingPointIeee754<Single>.Epsilon

获取可添加到 0 不会导致 0的最小值。

IFloatingPointIeee754<Single>.NaN

获取一个表示 NaN的值。

IFloatingPointIeee754<Single>.NegativeInfinity

获取一个表示负 infinity值的值。

IFloatingPointIeee754<Single>.NegativeZero

获取一个表示负 zero值的值。

IFloatingPointIeee754<Single>.PositiveInfinity

获取一个表示正 infinity值的值。

IIncrementOperators<Single>.Increment(Single)

递增值。

IMinMaxValue<Single>.MaxValue

获取当前类型的最大值。

IMinMaxValue<Single>.MinValue

获取当前类型的最小值。

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

将两个值相除以计算其模数或余数。

IMultiplicativeIdentity<Single,Single>.MultiplicativeIdentity

获取当前类型的乘法标识。

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

将两个值相乘以计算其产品。

INumberBase<Single>.IsCanonical(Single)

确定某个值是否在其规范表示形式中。

INumberBase<Single>.IsComplexNumber(Single)

确定值是否表示复数。

INumberBase<Single>.IsImaginaryNumber(Single)

确定值是否表示纯虚数。

INumberBase<Single>.IsZero(Single)

确定值是否为零。

INumberBase<Single>.One

获取类型的值 1

INumberBase<Single>.Radix

获取类型的基数。

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

表示单精度浮点数。

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

表示单精度浮点数。

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

表示单精度浮点数。

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

尝试将当前类型的实例转换为另一种类型,为超出当前类型可表示范围的任何值引发溢出异常。

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

尝试将当前类型的实例转换为另一种类型,使超出当前类型的可表示范围的任何值饱和。

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

尝试将当前类型的实例转换为另一种类型,截断属于当前类型的可表示范围之外的任何值。

INumberBase<Single>.Zero

获取类型的值 0

ISignedNumber<Single>.NegativeOne

获取类型的值 -1

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

减去两个值以计算其差异。

IUnaryNegationOperators<Single,Single>.UnaryNegation(Single)

计算值的一元求反。

IUnaryPlusOperators<Single,Single>.UnaryPlus(Single)

计算一元加值。

适用于

线程安全性

此类型的所有成员都是线程安全的。 似乎修改实例状态的成员实际上返回使用新值初始化的新实例。 与任何其他类型一样,读取和写入包含此类型的实例的共享变量必须受到锁的保护,以确保线程安全。

另请参阅