비고
이 문서는 이 API에 대한 참조 설명서를 보충하는 추가 설명을 제공합니다.
Single 값 형식은 음수 3.402823e38에서 양수 3.402823e38까지의 값과 양수 또는 음수 0, PositiveInfinity, NegativeInfinity및 숫자(NaN)가 아닌 단일 정밀도 32비트 숫자를 나타냅니다. 이는 매우 크거나(예: 행성이나 은하 사이의 거리) 또는 매우 작거나(예: 킬로그램 단위의 물질의 분자 질량) 종종 부정확한 값(예: 지구에서 다른 태양계까지의 거리)을 나타내기 위한 것입니다. Single 형식은 이진 부동 소수점 산술 연산에 대한 IEC 60559:1989(IEEE 754) 표준을 준수합니다.
System.Single 이 형식의 인스턴스를 비교하고, 인스턴스 값을 해당 문자열 표현으로 변환하고, 숫자의 문자열 표현을 이 형식의 인스턴스로 변환하는 메서드를 제공합니다. 서식 사양 코드가 값 형식의 문자열 표현을 제어하는 방법에 대한 자세한 내용은 형식, 표준 숫자 서식 문자열및 사용자 지정 숫자 서식 문자열 참조하세요.
부동 소수점 표현 및 정밀도
Single 데이터 형식은 다음 표와 같이 단정밀도 부동 소수점 값을 32비트 이진 형식으로 저장합니다.
| 부분 | 비트 |
|---|---|
| 가수(Significand) 또는 맨티사(mantissa) | 0-22 |
| 지수 | 23-30 |
| 기호(0 = 양수, 1 = 음수) | 31 |
소수 자릿수가 일부 분수 값(예: 1/3 또는 Math.PI)을 정확하게 나타낼 수 없는 것처럼 이진 분수는 일부 소수 값을 나타낼 수 없습니다. 예를 들어 .2로 정확하게 10진수로 표현되는 2/10은 .0011111001001100 이진 분수로 표현되며 패턴 "1100"은 무한대로 반복됩니다. 이 경우 부동 소수점 값은 나타내는 숫자의 부정확한 표현을 제공합니다. 원래 부동 소수점 값에 대해 추가 수학 연산을 수행하면 정밀도가 부족한 경우가 많습니다. 예를 들어 .3을 10으로 곱하고 .3을 .3에서 .3으로 9번 추가하는 결과를 비교하면 곱하기보다 8개의 연산이 더 많이 포함되므로 정확도가 낮은 결과가 생성됩니다. 이 차이는 두 Single 값을 "R" 표준 숫자 형식 문자열을 사용하여 표시할 때만 명백합니다. 이 형식은 필요한 경우 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.0000002
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와 1조의 곱을 더합니다. 그러나 제품이 너무 작아서 원래 부동 소수점 값을 수정할 수 없습니다. 가장 낮은 유효 자릿수는 천 번째인 반면, 제품에서 가장 중요한 숫자는 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 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).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 값을 원하는 전체 자릿수로 반올림하여 문제를 해결할 수 있습니다.
부동 소수점 숫자를 사용하는 수학 또는 비교 연산은 이진 부동 소수점 숫자가 10진수와 같지 않을 수 있으므로 소수점 숫자를 사용하는 경우 동일한 결과를 생성하지 못할 수 있습니다. 이전 예제에서는 .3을 10으로 곱하고 .3을 .3에 9번 추가하는 결과를 표시하여 이를 설명했습니다.
소수 자릿수 값이 있는 숫자 연산의 정확도가 중요한 경우 Decimal 형식 대신 Single 형식을 사용합니다. 정수 계열 값이 Int64 또는 UInt64 형식 범위를 벗어나는 숫자 연산의 정확도가 중요한 경우 BigInteger 형식을 사용합니다.
부동 소수점 숫자가 포함된 경우 값이 왕복 않을 수 있습니다. 연산이 원래의 부동 소수점 숫자를 다른 형태로 변환하고, 역연산이 그 변환된 형태를 다시 부동 소수점 숫자로 변환하며, 최종 부동 소수점 숫자가 원래의 부동 소수점 숫자와 같다면, 이러한 과정을 왕복 과정이라고 합니다. 변환 시 하나 이상의 유효 자릿수가 손실되거나 변경되어 왕복이 실패할 수 있습니다.
다음 예제에서는 세 Single 값이 문자열로 변환되고 파일에 저장됩니다. .NET Framework에서 이 예제를 실행하면 값이 동일한 것처럼 보이지만 복원된 값은 원래 값과 같지 않습니다. (이 문제는 이후 .NET에서 처리되었으며, 여기서 값은 올바르게 왕복합니다.)
StreamWriter sw = new(@"./Singles.dat"); float[] 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(); float[] restoredValues = new float[values.Length]; StreamReader sr = new(@"./Singles.dat"); string temp = sr.ReadToEnd(); string[] tempStrings = temp.Split('|'); for (int ctr = 0; ctr < tempStrings.Length; ctr++) restoredValues[ctr] = float.Parse(tempStrings[ctr]); for (int ctr = 0; ctr < values.Length; ctr++) Console.WriteLine($"{values[ctr]} {(values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>")} {restoredValues[ctr]}"); // The example displays the following output on .NET Framework: // 2.882883 <> 2.882883 // 0.3333333 <> 0.3333333 // 3.141593 <> 3.141593open 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 on .NET Framework: // 2.882883 <> 2.882883 // 0.3333333 <> 0.3333333 // 3.141593 <> 3.141593Dim 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 ' The example displays the following output on .NET Framework: ' 2.882883 <> 2.882883 ' 0.3333333 <> 0.3333333 ' 3.141593 <> 3.141593.NET Framework를 대상으로 하는 경우 "G9" 표준 숫자 형식 문자열을 사용하여 Single 값의 전체 정밀도를 보존함으로써 값을 성공적으로 되돌릴 수 있습니다.
Single 값은 Double 값보다 정밀도가 낮습니다. 변환 후 겉보기에 동등해 보이는 Single로 전환된 Double 값은 종종 정밀도의 차이로 인해 Double 값과 같지 않을 수 있습니다. 다음 예제에서는 동일한 나누기 작업의 결과가 Double 값과 Single 값에 할당됩니다. Single 값이 Double캐스팅된 후 두 값을 비교하면 같지 않음이 표시됩니다.
using System; public class Example9 { public static void Main() { 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: // 0.33333333333333331 = 0.3333333432674408: Falseopen 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: FalseModule Example10 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이 문제를 방지하려면 Double 데이터 형식 대신 Single 데이터 형식을 사용하거나 두 값의 전체 자릿수가 같도록 Round 메서드를 사용합니다.
동등성 검사
같게 간주하려면 두 Single 값이 동일한 값을 나타내야 합니다. 그러나 값 간의 정밀도 차이 또는 하나 또는 두 값 모두에 의한 정밀도 손실로 인해 동일할 것으로 예상되는 부동 소수점 값은 가장 낮은 유효 자릿수의 차이로 인해 같지 않은 것으로 판명되는 경우가 많습니다. 따라서 두 값이 같은지 여부를 확인하기 위해 Equals 메서드를 호출하거나 두 CompareTo 값 간의 관계를 확인하기 위해 Single 메서드를 호출하면 예기치 않은 결과가 발생하는 경우가 많습니다. 첫 번째 값의 전체 자릿수는 7자리이고 두 번째 값은 9이므로 다음 예제에서는 두 개의 분명히 같은 Single 값이 같지 않은 것으로 판명됩니다.
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}"
// 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
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
정밀도 손실이 비교 결과에 영향을 줄 가능성이 있는 경우 Equals 또는 CompareTo 메서드를 호출하는 대신 다음 기술을 사용할 수 있습니다.
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: Trueopen 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: TrueModule 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) 메서드를 참조하세요.
같음을 테스트하는 대신 대략적인 같음을 테스트합니다. 이 기술을 사용하려면 두 값이 다를 수 있지만 여전히 같을 수 있는 절대 크기를 정의하거나 더 작은 값이 더 큰 값과 다를 수 있는 상대 크기를 정의해야 합니다.
경고
Single.Epsilon 같음을 테스트할 때 두 Single 값 사이의 거리를 절대 측정값으로 사용하는 경우가 있습니다. 그러나 Single.Epsilon는 값이 0인 Single에 더하거나 뺄 수 있는 가능한 가장 작은 값을 측정합니다. 대부분의 양수 및 음수 Single 값의 경우 Single.Epsilon 값이 너무 작아 검색할 수 없습니다. 따라서 0인 값을 제외하고 같음 테스트에는 사용하지 않는 것이 좋습니다.
다음 예제에서는 후자의 방법을 사용하여 두 값 간의 상대적 차이를 테스트하는
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: Trueopen 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.0000001: False // 1 is approximately equal to 1.0000001: TruePublic 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
부동 소수점 값 및 예외
부동 소수점 값이 있는 작업은 정수 형식이 있는 작업과 달리 예외를 throw하지 않으며, 0으로 나누기 또는 오버플로와 같은 잘못된 작업의 경우 예외를 throw합니다. 대신 이러한 상황에서 부동 소수점 연산의 결과는 0, 양수 무한대, 음수 무한대 또는 숫자(NaN)가 아닙니다.
부동 소수점 연산의 결과가 대상 형식에 비해 너무 작으면 결과는 0입니다. 이 문제는 다음 예제와 같이 두 개의 매우 작은 부동 소수점 숫자를 곱할 때 발생할 수 있습니다.
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: Truelet 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: TrueModule 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부동 소수점 연산 결과의 크기가 대상 형식의 범위를 초과하는 경우, 결과의 부호에 따라 연산의 결과는 PositiveInfinity 또는 NegativeInfinity이 됩니다. 어떤 작업이 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: Trueopen 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: TrueModule 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: TruePositiveInfinity 또한 양의 배수를 0으로 나누기에서 비롯된 결과이며, NegativeInfinity은 음의 배수를 0으로 나누기에서 비롯된 결과입니다.
부동 소수점 연산이 유효하지 않으면 그 연산의 결과는 NaN입니다. 예를 들어, 다음 연산의 결과는 NaN입니다.
- 배당금이 0인 0으로 나누기. 다른 경우에 0으로 나누면 PositiveInfinity 또는 NegativeInfinity이 발생할 수 있음을 유의하십시오.
- 잘못된 입력이 있는 모든 부동 소수점 연산. 예를 들어 음수 값의 제곱근을 찾으려고 시도하면 NaN반환됩니다.
- 값이 Single.NaN인수가 있는 모든 연산입니다.
타입 변환
Single 구조체는 명시적 또는 암시적 변환 연산자를 정의하지 않습니다. 대신 변환은 컴파일러에 의해 구현됩니다.
다음 표에서는 다른 기본 숫자 형식의 값을 값으로 변환할 수 있는 Single 방법을 나열합니다. 또한 변환이 확대 또는 축소되는지 여부와 결과 Single 정밀도가 원래 값보다 작을 수 있는지 여부를 나타냅니다.
| 변환하기 | 확대/축소 | 가능한 정밀도 손실 |
|---|---|---|
| Byte | 확대 | 아니오 |
| Decimal | 확대 C#에는 캐스트 연산자가 필요합니다. |
예. Decimal 10진수 29자리의 정밀도를 지원합니다. Single 9를 지원합니다. |
| Double | 축소; 범위를 벗어난 값은 Double.NegativeInfinity 또는 Double.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)
또한 Double 값 Double.NaN, Double.PositiveInfinity및 Double.NegativeInfinity은 각각 Single.NaN, Single.PositiveInfinity및 Single.NegativeInfinity으로 변환됩니다.
일부 숫자 형식의 값을 Single 값으로 변환하면 정밀도가 떨어질 수 있습니다. 예제에서 알 수 있듯이 Decimal, Double, Int32, Int64, UInt32및 UInt64 값을 Single 값으로 변환할 때 정밀도 손실이 발생할 수 있습니다.
Single 값을 Double 변환하는 것은 확대 변환입니다. 변환은 Double 형식에 Single 값에 대한 정확한 표현이 없는 경우 정밀도가 손실될 수 있습니다.
Single 값을 Double 이외의 기본 숫자 데이터 형식 값으로 변환하려면 축소 변환이며 캐스트 연산자(C#) 또는 변환 메서드(Visual Basic)가 필요합니다. 대상 형식의 MinValue 및 MaxValue 속성으로 정의된 대상 데이터 형식의 범위를 벗어난 값은 다음 표와 같이 동작합니다.
| 대상 유형 | 결과 |
|---|---|
| 모든 정수 계열 형식 | 확인된 컨텍스트에서 변환이 발생하는 경우 OverflowException 예외입니다. 확인되지 않은 컨텍스트(C#의 기본값)에서 변환이 발생하면 변환 작업이 성공하지만 값이 오버플로됩니다. |
| Decimal | 예외입니다 OverflowException . |
또한 Single.NaN, Single.PositiveInfinity및 Single.NegativeInfinity는 확인된 컨텍스트에서 정수로 변환하기 위한 OverflowException을 던지지만, 이러한 값은 확인되지 않은 컨텍스트에서 정수로 변환될 때 오버플로가 발생합니다. Decimal변환을 할 때는 항상 OverflowException를 던집니다. Double변환의 경우 각각 Double.NaN, Double.PositiveInfinity및 Double.NegativeInfinity변환합니다.
숫자 변환 중 Single 값의 정밀도 손실이 발생할 수 있음을 유의하십시오. 예제의 출력과 같이 비계열 Single 값을 변환하는 경우 Single 값이 반올림되거나(Visual Basic에서와 같이) 잘리면(C# 및 F#에서와 같이) 소수 구성 요소가 손실됩니다. Decimal 값으로 변환하는 경우 Single 값에 대상 데이터 형식의 정확한 표현이 없을 수 있습니다.
다음 예제에서는 여러 Single 값을 다른 여러 숫자 형식으로 변환합니다. 변환은 Visual Basic(기본값), C#(확인된 키워드로 인해) 및 F#(open Checked 문으로 인해)의 확인된 컨텍스트에서 발생합니다. 예제의 출력은 확인된 선택되지 않은 컨텍스트 모두에서 변환 결과를 보여 줍니다.
/removeintchecks+ 컴파일러 스위치를 사용하여 컴파일하고, C#에서 checked 문을 주석으로 처리하고, F#에서 open Checked 문을 주석으로 처리하여 Visual Basic에서 확인되지 않은 컨텍스트에서 변환을 수행할 수 있습니다.
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 ∞ 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)
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 형식 변환 및 형식 변환 테이블참조하세요.
부동 소수점 기능
Single 구조 및 관련 형식은 다음과 같은 작업 범주를 수행하는 메서드를 제공합니다.
값의 비교입니다. Equals 메서드를 호출하여 두 Single 값이 같은지 또는 CompareTo 메서드를 호출하여 두 값 간의 관계를 확인할 수 있습니다.
Single 구조체는 전체 비교 연산자 집합도 지원합니다. 예를 들어 같음 또는 같지 않음을 테스트하거나 한 값이 다른 값보다 크거나 같은지 확인할 수 있습니다. 피연산자 중 하나가 Double경우 비교를 수행하기 전에 Single 값이 Double 변환됩니다. 피연산자 중 하나가 정수 형식인 경우 비교를 수행하기 전에 Single 변환됩니다. 이러한 변환은 확대되지만 정밀도 손실이 발생할 수 있습니다.
경고
정밀도의 차이로 인해 같을 것으로 예상되는 두 개의 Single 값이 같지 않은 것으로 판명되어 비교 결과에 영향을 줄 수 있습니다. 두 값을 비교하는 것에 대한 더 많은 정보를 보려면 Single 섹션을 참조하세요.
IsNaN, IsInfinity, IsPositiveInfinity및 IsNegativeInfinity 메서드를 호출하여 이러한 특수 값을 테스트할 수도 있습니다.
수학 연산. 더하기, 빼기, 곱하기 및 나누기와 같은 일반적인 산술 연산은 Single 메서드가 아닌 언어 컴파일러 및 CIL(공용 중간 언어) 명령에 의해 구현됩니다. 수학 연산의 다른 피연산자는 Double경우 연산을 수행하기 전에 SingleDouble 변환되고 연산 결과도 Double 값입니다. 다른 피연산자는 정수 계열 형식인 경우 작업을 수행하기 전에 Single 변환되며 작업의 결과도 Single 값입니다.
static클래스에서Shared(Visual Basic에서는System.Math) 메서드를 호출하여 다른 수학 연산을 수행할 수 있습니다. 여기에는 산술(예: Math.Abs, Math.Sign및 Math.Sqrt), 기하 도형(예: Math.Cos 및 Math.Sin) 및 미적분(예: Math.Log)에 일반적으로 사용되는 추가 메서드가 포함됩니다. 모든 경우에 Single 값은 Double변환됩니다.Single 값의 개별 비트를 조작할 수도 있습니다. BitConverter.GetBytes(Single) 메서드는 바이트 배열에서 비트 패턴을 반환합니다. 해당 바이트 배열을 BitConverter.ToInt32 메서드에 전달하면 Single 값의 비트 패턴을 32비트 정수로 유지할 수도 있습니다.
반올림. 반올림은 부동 소수점 표현과 정밀도 문제로 인해 발생하는 값 간의 차이를 줄이는 기술로 자주 사용됩니다. Single 메서드를 호출하여 Math.Round 값을 반올림할 수 있습니다. 그러나 메서드가 호출되기 전에 Single 값이 Double로 변환되며, 이 변환은 정밀도가 손실될 수 있습니다.
서식. Single 메서드를 호출하거나 ToString 기능을 사용하여 값을 문자열 표현으로 변환할 수 있습니다. 서식 문자열이 부동 소수점 값의 문자열 표현을 제어하는 방법에 대한 자세한 내용은 표준 숫자 형식 문자열 및 사용자 지정 숫자 형식 문자열을 참조하세요.
문자열구문 분석. Single 또는 Parse 메서드를 호출하여 부동 소수점 값의 문자열 표현을 TryParse 값으로 변환할 수 있습니다. 구문 분석 작업이 실패하면 Parse 메서드는 예외를 throw하는 반면 TryParse 메서드는
false반환합니다.형식 변환. Single 구조는 두 표준 .NET 데이터 형식 간의 변환을 지원하는 IConvertible 인터페이스에 대한 명시적 인터페이스 구현을 제공합니다. 언어 컴파일러는 DoubleSingle 값으로 변환하는 것을 제외하고 다른 모든 표준 숫자 형식에 대한 값의 암시적 변환도 지원합니다. Double 이외의 표준 숫자 형식의 값을 Single 변환하는 것은 확대 변환이며 캐스팅 연산자 또는 변환 메서드를 사용할 필요가 없습니다.
그러나 32비트 및 64비트 정수 값의 변환에는 정밀도 손실이 포함될 수 있습니다. 다음 표는 32비트, 64비트 및 Double 형식의 정밀도 차이를 나열합니다.
유형 최대 정밀도(10진수) 내부 정밀도 (소수 자릿수) Double 15 17 Int32 및 UInt32 10 10 Int64 및 UInt64 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: Falselet 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 on .NET: // 0.3333333333333333 = 0.3333333432674408: FalseDim 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
.NET