System.Single 구조체
이 문서에서는 이 API에 대한 참조 설명서에 대한 추가 설명서를 제공합니다.
값 형식은 Single 음수()가 아닌 음수 3.402823e38에서 양수 3.402823e38, 양수 또는 음수 0PositiveInfinityNegativeInfinity까지의 값을 가진 단정밀도 32비트 숫자를NaN 나타냅니다. 이는 매우 크거나(예: 행성이나 은하 사이의 거리) 또는 매우 작거나(예: 킬로그램 단위의 물질의 분자 질량) 종종 부정확한 값(예: 지구에서 다른 태양계까지의 거리)을 나타내기 위한 것입니다. 이 형식은 이 Single 진 부동 소수점 산술 연산에 대한 IEC 60559:1989(IEEE 754) 표준을 준수합니다.
System.Single 에서는 이 형식의 인스턴스를 비교하고, 인스턴스 값을 해당 문자열 표현으로 변환하고, 숫자의 문자열 표현을 이 형식의 인스턴스로 변환하는 메서드를 제공합니다. 형식 사양 코드가 값 형식의 문자열 표현을 제어하는 방법에 대한 자세한 내용은 서식 지정 형식, 표준 숫자 형식 문자열 및 사용자 지정 숫자 형식 문자열을 참조하세요.
부동 소수점 표현 및 정밀도
데이터 형식은 Single 다음 표와 같이 단정밀도 부동 소수점 값을 32비트 이진 형식으로 저장합니다.
요소 | Bits |
---|---|
Significand 또는 mantissa | 0-22 |
Exponent | 23-30 |
기호(0 = 양수, 1 = 음수) | 31 |
소수 자릿수가 일부 분수 값(예: 1/3 또는 Math.PI)을 정확하게 나타낼 수 없는 것처럼 이진 분수는 일부 소수 값을 나타낼 수 없습니다. 예를 들어 .2로 정확하게 10진수로 표현되는 2/10은 .0011111001001100 이진 분수로 표현되며 패턴 "1100"은 무한대로 반복됩니다. 이 경우 부동 소수점 값은 나타내는 숫자의 부정확한 표현을 제공합니다. 원래 부동 소수점 값에 대해 추가 수학 연산을 수행하면 정밀도가 부족한 경우가 많습니다. 예를 들어 .3을 10으로 곱하고 .3을 .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: {0:R}", result1);
Console.WriteLine(".2 Added 10 times: {0:R}", result2);
}
}
// The example displays the following output:
// .2 * 10: 2
// .2 Added 10 times: 2.00000024
let value = 0.2f
let result1 = value * 10f
let mutable result2 = 0f
for _ = 1 to 10 do
result2 <- result2 + value
printfn $".2 * 10: {result1:R}"
printfn $".2 Added 10 times: {result2:R}"
// The example displays the following output:
// .2 * 10: 2
// .2 Added 10 times: 2.00000024
Module 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.00000024
일부 숫자는 소수점 이진 값으로 정확하게 나타낼 수 없으므로 부동 소수점 숫자는 실제 숫자와 근사치일 수 있습니다.
모든 부동 소수점 숫자에는 제한된 수의 유효 자릿수가 있으며, 이는 부동 소수점 값이 실제 숫자와 얼마나 정확하게 일치하는지 결정합니다. 값의 Single 전체 자릿수는 최대 7자리이지만 내부적으로는 최대 9자리 자릿수가 기본. 즉, 일부 부동 소수점 연산에는 부동 소수점 값을 변경할 정밀도가 부족할 수 있습니다. 다음 예제에서는 큰 단정밀도 부동 소수점 값을 정의한 다음 곱 Single.Epsilon 과 4분의 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 Example9 { public static void Main() { Single[] values = { 10.01f, 2.88f, 2.88f, 2.88f, 9.0f }; Single result = 27.65f; Single total = 0f; foreach (var value in values) total += value; if (total.Equals(result)) Console.WriteLine("The sum of the values equals the total."); else Console.WriteLine("The sum of the values ({0}) does not equal the total ({1}).", total, result); } } // The example displays the following output: // The sum of the values (27.65) does not equal the total (27.65). // // If the index items in the Console.WriteLine statement are changed to {0:R}, // the example displays the following output: // The sum of the values (27.6500015) does not equal the total (27.65).
let values = [| 10.01f; 2.88f; 2.88f; 2.88f; 9f |] let result = 27.65f let mutable total = 0f for value in values do total <- total + value if total.Equals result then printfn "The sum of the values equals the total." else printfn "The sum of the values ({total}) does not equal the total ({result})." // The example displays the following output: // The sum of the values (27.65) does not equal the total (27.65). // // If the index items in the Console.WriteLine statement are changed to {0:R}, // the example displays the following output: // The sum of the values (27.6500015) does not equal the total (27.65).
Module Example10 Public Sub Main() Dim values() As Single = {10.01, 2.88, 2.88, 2.88, 9.0} Dim result As Single = 27.65 Dim total As Single For Each value In values total += value Next If total.Equals(result) Then Console.WriteLine("The sum of the values equals the total.") Else Console.WriteLine("The sum of the values ({0}) does not equal the total ({1}).", total, result) End If End Sub End Module ' The example displays the following output: ' The sum of the values (27.65) does not equal the total (27.65). ' ' If the index items in the Console.WriteLine statement are changed to {0:R}, ' the example displays the following output: ' The sum of the values (27.639999999999997) does not equal the total (27.64).
두 값의 모든 유효 자릿수 Single 를
{0:R}
{1:R}
표시하기 위해 문의{1}
{0}
서식 항목을 Console.WriteLine(String, Object, Object) 변경하는 경우 더하기 작업 중에 전체 자릿수가 손실되므로 두 값이 같지 않은 것이 분명합니다. 이 경우 비교를 수행하기 전에 메서드를 Math.Round(Double, Int32) 호출하여 값을 원하는 전체 자릿수로 반올림 Single 하여 문제를 해결할 수 있습니다.부동 소수점 숫자를 사용하는 수학 또는 비교 연산은 이진 부동 소수점 숫자가 10진수와 같지 않을 수 있으므로 소수점 숫자를 사용하는 경우 동일한 결과를 생성하지 못할 수 있습니다. 이전 예제에서는 .3을 10으로 곱하고 .3을 .3에 9번 추가하는 결과를 표시하여 이를 설명했습니다.
소수 자릿수 값을 사용하는 숫자 연산의 정확도가 중요한 경우 형식 대신 형식을 DecimalSingle 사용합니다. 정수 값이 또는 UInt64 형식 범위를 초과하는 숫자 연산의 Int64 정확도가 중요한 경우 형식을 BigInteger 사용합니다.
부동 소수점 숫자가 포함된 경우 값이 왕복하지 않을 수 있습니다. 값은 연산이 원래 부동 소수점 숫자를 다른 폼으로 변환하고, 역 연산이 변환된 폼을 다시 부동 소수점 숫자로 변환하고, 최종 부동 소수점 숫자가 원래 부동 소수점 숫자와 같으면 왕복이라고 합니다. 변환 시 하나 이상의 유효 자릿수가 손실되거나 변경되어 왕복이 실패할 수 있습니다. 다음 예제에서는 세 Single 개의 값이 문자열로 변환되어 파일에 저장됩니다. 출력에서와 같이 값이 동일해 보이지만 복원된 값은 원래 값과 같지 않습니다.
using System; using System.IO; public class Example10 { public static void Main() { StreamWriter sw = new StreamWriter(@".\Singles.dat"); Single[] values = { 3.2f / 1.11f, 1.0f / 3f, (float)Math.PI }; for (int ctr = 0; ctr < values.Length; ctr++) { sw.Write(values[ctr].ToString()); if (ctr != values.Length - 1) sw.Write("|"); } sw.Close(); Single[] restoredValues = new Single[values.Length]; StreamReader sr = new StreamReader(@".\Singles.dat"); string temp = sr.ReadToEnd(); string[] tempStrings = temp.Split('|'); for (int ctr = 0; ctr < tempStrings.Length; ctr++) restoredValues[ctr] = Single.Parse(tempStrings[ctr]); for (int ctr = 0; ctr < values.Length; ctr++) Console.WriteLine("{0} {2} {1}", values[ctr], restoredValues[ctr], values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>"); } } // The example displays the following output: // 2.882883 <> 2.882883 // 0.3333333 <> 0.3333333 // 3.141593 <> 3.141593
open System open System.IO let values = [| 3.2f / 1.11f; 1f / 3f; MathF.PI |] do use sw = new StreamWriter(@".\Singles.dat") for i = 0 to values.Length - 1 do sw.Write(string values[i]) if i <> values.Length - 1 then sw.Write "|" let restoredValues = use sr = new StreamReader(@".\Singles.dat") sr.ReadToEnd().Split '|' |> Array.map Single.Parse for i = 0 to values.Length - 1 do printfn $"""{values[i]} {if values[i].Equals restoredValues[i] then "=" else "<>"} {restoredValues[i]}""" // The example displays the following output: // 2.882883 <> 2.882883 // 0.3333333 <> 0.3333333 // 3.141593 <> 3.141593
Imports System.IO Module Example11 Public Sub Main() Dim sw As New StreamWriter(".\Singles.dat") Dim values() As Single = {3.2 / 1.11, 1.0 / 3, CSng(Math.PI)} For ctr As Integer = 0 To values.Length - 1 sw.Write(values(ctr).ToString()) If ctr <> values.Length - 1 Then sw.Write("|") Next sw.Close() Dim restoredValues(values.Length - 1) As Single Dim sr As New StreamReader(".\Singles.dat") Dim temp As String = sr.ReadToEnd() Dim tempStrings() As String = temp.Split("|"c) For ctr As Integer = 0 To tempStrings.Length - 1 restoredValues(ctr) = Single.Parse(tempStrings(ctr)) Next For ctr As Integer = 0 To values.Length - 1 Console.WriteLine("{0} {2} {1}", values(ctr), restoredValues(ctr), If(values(ctr).Equals(restoredValues(ctr)), "=", "<>")) Next End Sub End Module ' The example displays the following output: ' 2.882883 <> 2.882883 ' 0.3333333 <> 0.3333333 ' 3.141593 <> 3.141593
이 경우 다음 예제와 같이 "G9" 표준 숫자 서식 문자열 을 사용하여 값의 Single 전체 전체 전체 자릿수를 유지하여 값을 성공적으로 라운드트립할 수 있습니다.
using System; using System.IO; public class Example11 { public static void Main() { StreamWriter sw = new StreamWriter(@".\Singles.dat"); Single[] values = { 3.2f / 1.11f, 1.0f / 3f, (float)Math.PI }; for (int ctr = 0; ctr < values.Length; ctr++) sw.Write("{0:G9}{1}", values[ctr], ctr < values.Length - 1 ? "|" : ""); sw.Close(); Single[] restoredValues = new Single[values.Length]; StreamReader sr = new StreamReader(@".\Singles.dat"); string temp = sr.ReadToEnd(); string[] tempStrings = temp.Split('|'); for (int ctr = 0; ctr < tempStrings.Length; ctr++) restoredValues[ctr] = Single.Parse(tempStrings[ctr]); for (int ctr = 0; ctr < values.Length; ctr++) Console.WriteLine("{0} {2} {1}", values[ctr], restoredValues[ctr], values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>"); } } // The example displays the following output: // 2.882883 = 2.882883 // 0.3333333 = 0.3333333 // 3.141593 = 3.141593
open System open System.IO let values = [| 3.2f / 1.11f; 1f / 3f; MathF.PI |] do use sw = new StreamWriter(@".\Singles.dat") for i = 0 to values.Length - 1 do sw.Write $"""{values[i]:G9}{if i < values.Length - 1 then "|" else ""}""" let restoredValues = use sr = new StreamReader(@".\Singles.dat") sr.ReadToEnd().Split '|' |> Array.map Single.Parse for i = 0 to values.Length - 1 do printfn $"""{values[i]} {if values[i].Equals restoredValues[i] then "=" else "<>"} {restoredValues[i]}""" // The example displays the following output: // 2.882883 = 2.882883 // 0.3333333 = 0.3333333 // 3.141593 = 3.141593
Imports System.IO Module Example12 Public Sub Main() Dim sw As New StreamWriter(".\Singles.dat") Dim values() As Single = {3.2 / 1.11, 1.0 / 3, CSng(Math.PI)} For ctr As Integer = 0 To values.Length - 1 sw.Write("{0:G9}{1}", values(ctr), If(ctr < values.Length - 1, "|", "")) Next sw.Close() Dim restoredValues(values.Length - 1) As Single Dim sr As New StreamReader(".\Singles.dat") Dim temp As String = sr.ReadToEnd() Dim tempStrings() As String = temp.Split("|"c) For ctr As Integer = 0 To tempStrings.Length - 1 restoredValues(ctr) = Single.Parse(tempStrings(ctr)) Next For ctr As Integer = 0 To values.Length - 1 Console.WriteLine("{0} {2} {1}", values(ctr), restoredValues(ctr), If(values(ctr).Equals(restoredValues(ctr)), "=", "<>")) Next End Sub End Module ' The example displays the following output: ' 2.882883 = 2.882883 ' 0.3333333 = 0.3333333 ' 3.141593 = 3.141593
Single 값은 값보다 Double 정밀도가 낮습니다. Single 겉보기에 동등한 Double 값으로 변환되는 값은 정밀도 차이로 인해 값과 같지 Double 않은 경우가 많습니다. 다음 예제에서는 동일한 나누기 작업의 결과가 값과 Single 값에 Double 할당됩니다. 값이 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("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2)); } } // The example displays the following output: // 0.33333333333333331 = 0.3333333432674408: False
open System let value1 = 1. / 3. let sValue2 = 1f /3f let value2 = double sValue2 printfn $"{value1:R} = {value2:R}: {value1.Equals value2}" // The example displays the following output: // 0.33333333333333331 = 0.3333333432674408: False
Module 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
이 문제를 방지하려면 데이터 형식 대신 데이터 형식을 Single 사용 Double 하거나 두 값의 전체 자릿수가 같도록 메서드를 사용합니다Round.
같음 테스트
같게 간주하려면 두 Single 값이 동일한 값을 나타내야 합니다. 그러나 값 간의 정밀도 차이 또는 하나 또는 두 값 모두에 의한 정밀도 손실로 인해 동일할 것으로 예상되는 부동 소수점 값은 가장 낮은 유효 자릿수의 차이로 인해 같지 않은 것으로 판명되는 경우가 많습니다. 따라서 두 값이 Equals 같은지 여부를 확인하기 위해 메서드를 호출하거나 두 Single 값 간의 관계를 확인하기 위해 CompareTo 메서드를 호출하면 예기치 않은 결과가 발생하는 경우가 많습니다. 첫 번째 값의 전체 자릿수는 7자리이고 두 번째 값은 9이기 때문에 두 개의 분명히 같은 Single 값이 같지 않은 것으로 판명되는 다음 예제에서는 분명합니다.
using System;
public class Example
{
public static void Main()
{
float value1 = .3333333f;
float value2 = 1.0f/3;
Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2));
}
}
// The example displays the following output:
// 0.3333333 = 0.333333343: False
let value1 = 0.3333333f
let value2 = 1f / 3f
printfn $"{value1:R} = {value2:R}: {value1.Equals value2}"
// The example displays the following output:
// 0.3333333 = 0.333333343: False
Module 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 값이 제곱되고 제곱근이 계산되어 원래 값을 복원합니다. 1초 Single 는 3.51을 곱한 후 결과의 제곱근을 3.51로 나누어 원래 값을 복원합니다. 두 값이 동일한 것처럼 보이지만 메서드를 호출하면 Equals(Single) 값이 같지 않음을 나타냅니다. "G9" 표준 형식 문자열을 사용하여 각 Single 값의 모든 유효 자릿수를 표시하는 결과 문자열을 반환하면 두 번째 값이 첫 번째 값보다 0000000000001 작음이 표시됩니다.
using System;
public class Example1
{
public static void Main()
{
float value1 = 10.201438f;
value1 = (float)Math.Sqrt((float)Math.Pow(value1, 2));
float value2 = (float)Math.Pow((float)value1 * 3.51f, 2);
value2 = ((float)Math.Sqrt(value2)) / 3.51f;
Console.WriteLine("{0} = {1}: {2}\n",
value1, value2, value1.Equals(value2));
Console.WriteLine("{0:G9} = {1:G9}", value1, value2);
}
}
// The example displays the following output:
// 10.20144 = 10.20144: False
//
// 10.201438 = 10.2014389
let value1 =
10.201438f ** 2f
|> sqrt
let value2 =
((value1 * 3.51f) ** 2f |> sqrt) / 3.51f
printfn $"{value1} = {value2}: {value1.Equals value2}\n"
printfn $"{value1:G9} = {value2:G9}"
// The example displays the following output:
// 10.20144 = 10.20144: False
//
// 10.201438 = 10.2014389
Module Example2
Public Sub Main()
Dim value1 As Single = 10.201438
value1 = CSng(Math.Sqrt(CSng(Math.Pow(value1, 2))))
Dim value2 As Single = CSng(Math.Pow(value1 * CSng(3.51), 2))
value2 = CSng(Math.Sqrt(value2) / CSng(3.51))
Console.WriteLine("{0} = {1}: {2}",
value1, value2, value1.Equals(value2))
Console.WriteLine()
Console.WriteLine("{0:G9} = {1:G9}", value1, value2)
End Sub
End Module
' The example displays the following output:
' 10.20144 = 10.20144: False
'
' 10.201438 = 10.2014389
정밀도 손실이 비교 결과에 영향을 줄 가능성이 있는 경우 또는 CompareTo 메서드를 호출 Equals 하는 대신 다음 기술을 사용할 수 있습니다.
메서드를 Math.Round 호출하여 두 값의 전체 자릿수가 같은지 확인합니다. 다음 예제에서는 두 개의 소수 값이 동일하도록 이 방법을 사용하도록 이전 예제를 수정합니다.
using System; public class Example2 { public static void Main() { float value1 = .3333333f; float value2 = 1.0f / 3; int precision = 7; value1 = (float)Math.Round(value1, precision); value2 = (float)Math.Round(value2, precision); Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2)); } } // The example displays the following output: // 0.3333333 = 0.3333333: True
open System let value1 = 0.3333333f let value2 = 1f / 3f let precision = 7 let value1r = Math.Round(float value1, precision) |> float32 let value2r = Math.Round(float value2, precision) |> float32 printfn $"{value1:R} = {value2:R}: {value1.Equals value2}" // The example displays the following output: // 0.3333333 = 0.3333333: True
Module 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 값이 0인 값에 추가하거나 뺄 수 있는 Single 가능한 가장 작은 값을 측정합니다. 대부분의 양수 및 음수 Single 값의 Single.Epsilon 경우 값이 너무 작아서 검색할 수 없습니다. 따라서 0인 값을 제외하고 같음 테스트에는 사용하지 않는 것이 좋습니다.
다음 예제에서는 후자의 방법을 사용하여 두 값 간의 상대적 차이를 테스트하는 메서드를 정의
IsApproximatelyEqual
합니다. 또한 메서드 및 메서드에 대한IsApproximatelyEqual
호출의 결과와 대조됩니다 Equals(Single) .using System; public class Example3 { public static void Main() { float one1 = .1f * 10; float one2 = 0f; for (int ctr = 1; ctr <= 10; ctr++) one2 += .1f; Console.WriteLine("{0:R} = {1:R}: {2}", one1, one2, one1.Equals(one2)); Console.WriteLine("{0:R} is approximately equal to {1:R}: {2}", one1, one2, IsApproximatelyEqual(one1, one2, .000001f)); } static bool IsApproximatelyEqual(float value1, float value2, float epsilon) { // If they are equal anyway, just return True. if (value1.Equals(value2)) return true; // Handle NaN, Infinity. if (Double.IsInfinity(value1) | Double.IsNaN(value1)) return value1.Equals(value2); else if (Double.IsInfinity(value2) | Double.IsNaN(value2)) return value1.Equals(value2); // Handle zero to avoid division by zero double divisor = Math.Max(value1, value2); if (divisor.Equals(0)) divisor = Math.Min(value1, value2); return Math.Abs(value1 - value2) / divisor <= epsilon; } } // The example displays the following output: // 1 = 1.00000012: False // 1 is approximately equal to 1.00000012: True
open System let isApproximatelyEqual value1 value2 epsilon = // If they are equal anyway, just return True. if value1.Equals value2 then true // Handle NaN, Infinity. elif Single.IsInfinity value1 || Single.IsNaN value1 then value1.Equals value2 elif Single.IsInfinity value2 || Single.IsNaN value2 then value1.Equals value2 else // Handle zero to avoid division by zero let divisor = max value1 value2 let divisor = if divisor.Equals 0 then min value1 value2 else divisor abs (value1 - value2) / divisor <= epsilon let one1 = 0.1f * 10f let mutable one2 = 0f for _ = 1 to 10 do one2 <- one2 + 0.1f printfn $"{one1:R} = {one2:R}: {one1.Equals one2}" printfn $"{one1:R} is approximately equal to {one2:R}: {isApproximatelyEqual one1 one2 0.000001f}" // The example displays the following output: // 1 = 1.00000012: False // 1 is approximately equal to 1.00000012: True
Module Example4 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 End Module ' The example displays the following output: ' 1 = 1.00000012: False ' 1 is approximately equal to 1.00000012: True
부동 소수점 값 및 예외
부동 소수점 값이 있는 작업은 정수 형식이 있는 작업과 달리 예외를 throw하지 않으며, 0으로 나누기 또는 오버플로와 같은 잘못된 작업의 경우 예외를 throw합니다. 대신 이러한 상황에서 부동 소수점 연산의 결과는 0, 양수 무한대, 음수 무한대 또는 숫자(NaN)가 아닙니다.
부동 소수점 연산의 결과가 대상 형식에 비해 너무 작으면 결과는 0입니다. 이 문제는 다음 예제와 같이 두 개의 매우 작은 부동 소수점 숫자를 곱할 때 발생할 수 있습니다.
using System; public class Example6 { public static void Main() { float value1 = 1.163287e-36f; float value2 = 9.164234e-25f; float result = value1 * value2; Console.WriteLine("{0} * {1} = {2}", value1, value2, result); Console.WriteLine("{0} = 0: {1}", result, result.Equals(0.0f)); } } // The example displays the following output: // 1.163287E-36 * 9.164234E-25 = 0 // 0 = 0: True
let value1 = 1.163287e-36f let value2 = 9.164234e-25f let result = value1 * value2 printfn $"{value1} * {value2} = {result}" printfn $"{result} = 0: {result.Equals(0f)}" // The example displays the following output: // 1.163287E-36 * 9.164234E-25 = 0 // 0 = 0: True
Module 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
부동 소수점 연산 결과의 크기가 대상 형식의 범위를 초과하는 경우 작업의 결과는 결과의 부호에 적합하거나 NegativeInfinity적절한 결과입니다PositiveInfinity. 오버플로 Single.MaxValuePositiveInfinity되는 작업의 결과는 다음 예제와 같이 오버플로 Single.MinValue 되는 작업의 결과입니다 NegativeInfinity.
using System; public class Example7 { public static void Main() { float value1 = 3.065e35f; float value2 = 6.9375e32f; float result = value1 * value2; Console.WriteLine("PositiveInfinity: {0}", Single.IsPositiveInfinity(result)); Console.WriteLine("NegativeInfinity: {0}\n", Single.IsNegativeInfinity(result)); value1 = -value1; result = value1 * value2; Console.WriteLine("PositiveInfinity: {0}", Single.IsPositiveInfinity(result)); Console.WriteLine("NegativeInfinity: {0}", Single.IsNegativeInfinity(result)); } } // The example displays the following output: // PositiveInfinity: True // NegativeInfinity: False // // PositiveInfinity: False // NegativeInfinity: True
open System let value1 = 3.065e35f let value2 = 6.9375e32f let result = value1 * value2 printfn $"PositiveInfinity: {Single.IsPositiveInfinity result}" printfn $"NegativeInfinity: {Single.IsNegativeInfinity result}\n" let value3 = -value1 let result2 = value3 * value2 printfn $"PositiveInfinity: {Single.IsPositiveInfinity result}" printfn $"NegativeInfinity: {Single.IsNegativeInfinity result}" // The example displays the following output: // PositiveInfinity: True // NegativeInfinity: False // // PositiveInfinity: False // NegativeInfinity: True
Module 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 또한 배당금이 양수인 0으로 나눠지고, NegativeInfinity 음수 배당금이 있는 0으로 나누기 결과도 발생합니다.
부동 소수점 연산이 유효하지 않은 경우 작업의 결과는 다음과 입니다 NaN. 예를 들어 NaN 다음 작업의 결과는 다음과 같습니다.
- 배당금이 0인 0으로 나누기. 0으로 나누기의 다른 경우는 둘 중 하나 PositiveInfinity 또는 NegativeInfinity.
- 잘못된 입력이 있는 모든 부동 소수점 작업입니다. 예를 들어 음수 값의 제곱근을 찾으려고 시도하면 반환됩니다 NaN.
- 값이 .인 인수가 있는 모든 연산입니다 Single.NaN.
형식 변환
구조체는 Single 명시적 또는 암시적 변환 연산자를 정의하지 않고 대신 컴파일러에서 변환을 구현합니다.
다음 표에서는 다른 기본 숫자 형식의 값을 값으로 변환할 Single 수 있는 방법을 나열합니다. 변환이 확대 또는 축소되는지 여부와 결과 Single 정밀도가 원래 값보다 작을 수 있는지 여부도 나타냅니다.
B*에서 A*로의 변환이 | 확대/축소 | 가능한 정밀도 손실 |
---|---|---|
Byte | Widening | 아니요 |
Decimal | Widening C#에는 캐스트 연산자가 필요합니다. |
예. Decimal 는 10진수 29자리의 정밀도를 지원합니다. Single 는 9를 지원합니다. |
Double | 축소; 범위를 벗어난 값이 변환 Double.NegativeInfinity 되거나 Double.PositiveInfinity. | 예. Double 는 17진수의 정밀도를 지원합니다. Single 는 9를 지원합니다. |
Int16 | Widening | 아니요 |
Int32 | Widening | 예. Int32 는 10진수의 정밀도를 지원합니다. Single 는 9를 지원합니다. |
Int64 | Widening | 예. Int64 는 19진수의 정밀도를 지원합니다. Single 는 9를 지원합니다. |
SByte | Widening | 아니요 |
UInt16 | Widening | 아니요 |
UInt32 | Widening | 예. UInt32 는 10진수의 정밀도를 지원합니다. Single 는 9를 지원합니다. |
UInt64 | Widening | 예. Int64 는 10진수 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("{0} ({1}) --> {2:R} ({3})",
value, value.GetType().Name,
sngValue, sngValue.GetType().Name);
}
}
}
// The example displays the following output:
// 0 (Byte) --> 0 (Single)
// 255 (Byte) --> 255 (Single)
// -79228162514264337593543950335 (Decimal) --> -7.92281625E+28 (Single)
// 79228162514264337593543950335 (Decimal) --> 7.92281625E+28 (Single)
// -1.79769313486232E+308 (Double) --> -Infinity (Single)
// 1.79769313486232E+308 (Double) --> Infinity (Single)
// -32768 (Int16) --> -32768 (Single)
// 32767 (Int16) --> 32767 (Single)
// -2147483648 (Int32) --> -2.14748365E+09 (Single)
// 2147483647 (Int32) --> 2.14748365E+09 (Single)
// -9223372036854775808 (Int64) --> -9.223372E+18 (Single)
// 9223372036854775807 (Int64) --> 9.223372E+18 (Single)
// -128 (SByte) --> -128 (Single)
// 127 (SByte) --> 127 (Single)
// 0 (UInt16) --> 0 (Single)
// 65535 (UInt16) --> 65535 (Single)
// 0 (UInt32) --> 0 (Single)
// 4294967295 (UInt32) --> 4.2949673E+09 (Single)
// 0 (UInt64) --> 0 (Single)
// 18446744073709551615 (UInt64) --> 1.84467441E+19 (Single)
open System
let values: obj list =
[ Byte.MinValue; Byte.MaxValue; Decimal.MinValue
Decimal.MaxValue; Double.MinValue; Double.MaxValue
Int16.MinValue; Int16.MaxValue; Int32.MinValue
Int32.MaxValue; Int64.MinValue; Int64.MaxValue
SByte.MinValue; SByte.MaxValue; UInt16.MinValue
UInt16.MaxValue; UInt32.MinValue; UInt32.MaxValue
UInt64.MinValue; UInt64.MaxValue ]
for value in values do
let sngValue =
match value with
| :? byte as v -> float32 v
| :? decimal as v -> float32 v
| :? double as v -> float32 v
| :? int16 as v -> float32 v
| :? int as v -> float32 v
| :? int64 as v -> float32 v
| :? int8 as v -> float32 v
| :? uint16 as v -> float32 v
| :? uint as v -> float32 v
| :? uint64 as v -> float32 v
| _ -> raise (NotImplementedException "Unknown Type")
printfn $"{value} ({value.GetType().Name}) --> {sngValue:R} ({sngValue.GetType().Name})"
// The example displays the following output:
// 0 (Byte) --> 0 (Single)
// 255 (Byte) --> 255 (Single)
// -79228162514264337593543950335 (Decimal) --> -7.92281625E+28 (Single)
// 79228162514264337593543950335 (Decimal) --> 7.92281625E+28 (Single)
// -1.79769313486232E+308 (Double) --> -Infinity (Single)
// 1.79769313486232E+308 (Double) --> Infinity (Single)
// -32768 (Int16) --> -32768 (Single)
// 32767 (Int16) --> 32767 (Single)
// -2147483648 (Int32) --> -2.14748365E+09 (Single)
// 2147483647 (Int32) --> 2.14748365E+09 (Single)
// -9223372036854775808 (Int64) --> -9.223372E+18 (Single)
// 9223372036854775807 (Int64) --> 9.223372E+18 (Single)
// -128 (SByte) --> -128 (Single)
// 127 (SByte) --> 127 (Single)
// 0 (UInt16) --> 0 (Single)
// 65535 (UInt16) --> 65535 (Single)
// 0 (UInt32) --> 0 (Single)
// 4294967295 (UInt32) --> 4.2949673E+09 (Single)
// 0 (UInt64) --> 0 (Single)
// 18446744073709551615 (UInt64) --> 1.84467441E+19 (Single)
Module 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 및 각각 , 및 Single.NegativeInfinity로 Single.NaNSingle.PositiveInfinity변환합니다.Double.NegativeInfinityDouble.PositiveInfinityDouble.NaN
일부 숫자 형식의 값을 값으로 Single 변환하면 정밀도 손실이 포함될 수 있습니다. 예제에서 알 수 있듯이 , Double, Int32UInt32Int64UInt64 및 값을 값으로 변환할 Decimal때 정밀도 손실이 발생할 수 Single 있습니다.
값을 a Double 로 Single 변환하는 것은 확대 변환입니다. 형식에 값에 대한 Single 정확한 표현이 없는 경우 Double 변환으로 인해 정밀도가 손실될 수 있습니다.
값을 1 Single 이 아닌 Double 기본 숫자 데이터 형식의 값으로 변환하는 것은 축소 변환이며 캐스트 연산자(C#) 또는 변환 메서드(Visual Basic의 경우)가 필요합니다. 대상 형식 및 속성에 의해 정의된 대상 데이터 형식의 MinValue
범위를 벗어난 값은 다음 표와 MaxValue
같이 동작합니다.
대상 형식 | 결과 |
---|---|
모든 정수 계열 형식 | OverflowException 검사 컨텍스트에서 변환이 발생하는 경우 예외입니다. 변환이 검사 없는 컨텍스트(C#의 기본값)에서 발생하는 경우 변환 작업은 성공하지만 값은 오버플로됩니다. |
Decimal | 예외,OverflowException |
또한 Single.NaN검사 Single.PositiveInfinitySingle.NegativeInfinity 컨텍스트에서 정수로의 변환을 위해 throw OverflowException 하지만, 이러한 값은 검사 없는 컨텍스트에서 정수로 변환될 때 오버플로됩니다. 변환의 Decimal경우 항상 을 throw합니다 OverflowException. 변환의 Double경우 각각 , Double.PositiveInfinity및 Double.NegativeInfinity로 Double.NaN변환됩니다.
전체 자릿수가 손실되면 값을 다른 숫자 형식으로 Single 변환할 수 있습니다. 정수가 Single 아닌 값을 변환하는 경우 예제의 출력과 같이 값이 반올림되거나(Visual Basic에서와 같이) 잘리면(C# 및 F#에서와 같이) 소수 구성 요소가 손실 Single 됩니다. 값으로 변환하는 Decimal 경우 값에 Single 대상 데이터 형식의 정확한 표현이 없을 수 있습니다.
다음 예제에서는 여러 Single 값을 다른 여러 숫자 형식으로 변환합니다. 변환은 Visual Basic(기본값), C#(검사ed 키워드(keyword)) 및 F#(문 때문에)의 open Checked
검사 컨텍스트에서 발생합니다. 이 예제의 출력은 검사 검사 없는 컨텍스트의 변환 결과를 보여 줍니다. 컴파일러 스위치를 사용하여 컴파일하고, C#에서 문을 주석으로 처리하고/removeintchecks+
, F#에서 문을 주석 checked
으로 처리하여 Visual Basic에서 검사 없는 컨텍스트에서 변환을 open Checked
수행할 수 있습니다.
using System;
public class Example5
{
public static void Main()
{
float[] values = { Single.MinValue, -67890.1234f, -12345.6789f,
12345.6789f, 67890.1234f, Single.MaxValue,
Single.NaN, Single.PositiveInfinity,
Single.NegativeInfinity };
checked
{
foreach (var value in values)
{
try
{
Int64 lValue = (long)value;
Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
value, value.GetType().Name,
lValue, lValue.GetType().Name);
}
catch (OverflowException)
{
Console.WriteLine("Unable to convert {0} to Int64.", value);
}
try
{
UInt64 ulValue = (ulong)value;
Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
value, value.GetType().Name,
ulValue, ulValue.GetType().Name);
}
catch (OverflowException)
{
Console.WriteLine("Unable to convert {0} to UInt64.", value);
}
try
{
Decimal dValue = (decimal)value;
Console.WriteLine("{0} ({1}) --> {2} ({3})",
value, value.GetType().Name,
dValue, dValue.GetType().Name);
}
catch (OverflowException)
{
Console.WriteLine("Unable to convert {0} to Decimal.", value);
}
Double dblValue = value;
Console.WriteLine("{0} ({1}) --> {2} ({3})",
value, value.GetType().Name,
dblValue, dblValue.GetType().Name);
Console.WriteLine();
}
}
}
}
// The example displays the following output for conversions performed
// in a checked context:
// Unable to convert -3.402823E+38 to Int64.
// Unable to convert -3.402823E+38 to UInt64.
// Unable to convert -3.402823E+38 to Decimal.
// -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
//
// -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
// Unable to convert -67890.13 to UInt64.
// -67890.13 (Single) --> -67890.12 (Decimal)
// -67890.13 (Single) --> -67890.125 (Double)
//
// -12345.68 (Single) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
// Unable to convert -12345.68 to UInt64.
// -12345.68 (Single) --> -12345.68 (Decimal)
// -12345.68 (Single) --> -12345.6787109375 (Double)
//
// 12345.68 (Single) --> 12345 (0x0000000000003039) (Int64)
// 12345.68 (Single) --> 12345 (0x0000000000003039) (UInt64)
// 12345.68 (Single) --> 12345.68 (Decimal)
// 12345.68 (Single) --> 12345.6787109375 (Double)
//
// 67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
// 67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
// 67890.13 (Single) --> 67890.12 (Decimal)
// 67890.13 (Single) --> 67890.125 (Double)
//
// Unable to convert 3.402823E+38 to Int64.
// Unable to convert 3.402823E+38 to UInt64.
// Unable to convert 3.402823E+38 to Decimal.
// 3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
//
// Unable to convert NaN to Int64.
// Unable to convert NaN to UInt64.
// Unable to convert NaN to Decimal.
// NaN (Single) --> NaN (Double)
//
// Unable to convert Infinity to Int64.
// Unable to convert Infinity to UInt64.
// Unable to convert Infinity to Decimal.
// Infinity (Single) --> Infinity (Double)
//
// Unable to convert -Infinity to Int64.
// Unable to convert -Infinity to UInt64.
// Unable to convert -Infinity to Decimal.
// -Infinity (Single) --> -Infinity (Double)
// The example displays the following output for conversions performed
// in an unchecked context:
// -3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// -3.402823E+38 (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
// Unable to convert -3.402823E+38 to Decimal.
// -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
//
// -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
// -67890.13 (Single) --> 18446744073709483726 (0xFFFFFFFFFFFEF6CE) (UInt64)
// -67890.13 (Single) --> -67890.12 (Decimal)
// -67890.13 (Single) --> -67890.125 (Double)
//
// -12345.68 (Single) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
// -12345.68 (Single) --> 18446744073709539271 (0xFFFFFFFFFFFFCFC7) (UInt64)
// -12345.68 (Single) --> -12345.68 (Decimal)
// -12345.68 (Single) --> -12345.6787109375 (Double)
//
// 12345.68 (Single) --> 12345 (0x0000000000003039) (Int64)
// 12345.68 (Single) --> 12345 (0x0000000000003039) (UInt64)
// 12345.68 (Single) --> 12345.68 (Decimal)
// 12345.68 (Single) --> 12345.6787109375 (Double)
//
// 67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
// 67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
// 67890.13 (Single) --> 67890.12 (Decimal)
// 67890.13 (Single) --> 67890.125 (Double)
//
// 3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// 3.402823E+38 (Single) --> 0 (0x0000000000000000) (UInt64)
// Unable to convert 3.402823E+38 to Decimal.
// 3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
//
// NaN (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// NaN (Single) --> 0 (0x0000000000000000) (UInt64)
// Unable to convert NaN to Decimal.
// NaN (Single) --> NaN (Double)
//
// Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// Infinity (Single) --> 0 (0x0000000000000000) (UInt64)
// Unable to convert Infinity to Decimal.
// Infinity (Single) --> Infinity (Double)
//
// -Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// -Infinity (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
// Unable to convert -Infinity to Decimal.
// -Infinity (Single) --> -Infinity (Double)
open System
open Checked
let values =
[ Single.MinValue; -67890.1234f; -12345.6789f
12345.6789f; 67890.1234f; Single.MaxValue
Single.NaN; Single.PositiveInfinity
Single.NegativeInfinity ]
for value in values do
try
let lValue = int64 value
printfn $"{value} ({value.GetType().Name}) --> {lValue} (0x{lValue:X16}) ({lValue.GetType().Name})"
with :? OverflowException ->
printfn $"Unable to convert {value} to Int64."
try
let ulValue = uint64 value
printfn $"{value} ({value.GetType().Name}) --> {ulValue} (0x{ulValue:X16}) ({ulValue.GetType().Name})"
with :? OverflowException ->
printfn $"Unable to convert {value} to UInt64."
try
let dValue = decimal value
printfn $"{value} ({value.GetType().Name}) --> {dValue} ({dValue.GetType().Name})"
with :? OverflowException ->
printfn $"Unable to convert {value} to Decimal."
let dblValue = double value
printfn $"{value} ({value.GetType().Name}) --> {dblValue} ({dblValue.GetType().Name})\n"
// The example displays the following output for conversions performed
// in a checked context:
// Unable to convert -3.402823E+38 to Int64.
// Unable to convert -3.402823E+38 to UInt64.
// Unable to convert -3.402823E+38 to Decimal.
// -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
//
// -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
// Unable to convert -67890.13 to UInt64.
// -67890.13 (Single) --> -67890.12 (Decimal)
// -67890.13 (Single) --> -67890.125 (Double)
//
// -12345.68 (Single) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
// Unable to convert -12345.68 to UInt64.
// -12345.68 (Single) --> -12345.68 (Decimal)
// -12345.68 (Single) --> -12345.6787109375 (Double)
//
// 12345.68 (Single) --> 12345 (0x0000000000003039) (Int64)
// 12345.68 (Single) --> 12345 (0x0000000000003039) (UInt64)
// 12345.68 (Single) --> 12345.68 (Decimal)
// 12345.68 (Single) --> 12345.6787109375 (Double)
//
// 67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
// 67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
// 67890.13 (Single) --> 67890.12 (Decimal)
// 67890.13 (Single) --> 67890.125 (Double)
//
// Unable to convert 3.402823E+38 to Int64.
// Unable to convert 3.402823E+38 to UInt64.
// Unable to convert 3.402823E+38 to Decimal.
// 3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
//
// Unable to convert NaN to Int64.
// Unable to convert NaN to UInt64.
// Unable to convert NaN to Decimal.
// NaN (Single) --> NaN (Double)
//
// Unable to convert Infinity to Int64.
// Unable to convert Infinity to UInt64.
// Unable to convert Infinity to Decimal.
// Infinity (Single) --> Infinity (Double)
//
// Unable to convert -Infinity to Int64.
// Unable to convert -Infinity to UInt64.
// Unable to convert -Infinity to Decimal.
// -Infinity (Single) --> -Infinity (Double)
// The example displays the following output for conversions performed
// in an unchecked context:
// -3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// -3.402823E+38 (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
// Unable to convert -3.402823E+38 to Decimal.
// -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
//
// -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
// -67890.13 (Single) --> 18446744073709483726 (0xFFFFFFFFFFFEF6CE) (UInt64)
// -67890.13 (Single) --> -67890.12 (Decimal)
// -67890.13 (Single) --> -67890.125 (Double)
//
// -12345.68 (Single) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
// -12345.68 (Single) --> 18446744073709539271 (0xFFFFFFFFFFFFCFC7) (UInt64)
// -12345.68 (Single) --> -12345.68 (Decimal)
// -12345.68 (Single) --> -12345.6787109375 (Double)
//
// 12345.68 (Single) --> 12345 (0x0000000000003039) (Int64)
// 12345.68 (Single) --> 12345 (0x0000000000003039) (UInt64)
// 12345.68 (Single) --> 12345.68 (Decimal)
// 12345.68 (Single) --> 12345.6787109375 (Double)
//
// 67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
// 67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
// 67890.13 (Single) --> 67890.12 (Decimal)
// 67890.13 (Single) --> 67890.125 (Double)
//
// 3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// 3.402823E+38 (Single) --> 0 (0x0000000000000000) (UInt64)
// Unable to convert 3.402823E+38 to Decimal.
// 3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
//
// NaN (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// NaN (Single) --> 0 (0x0000000000000000) (UInt64)
// Unable to convert NaN to Decimal.
// NaN (Single) --> NaN (Double)
//
// Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// Infinity (Single) --> 0 (0x0000000000000000) (UInt64)
// Unable to convert Infinity to Decimal.
// Infinity (Single) --> Infinity (Double)
//
// -Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
// -Infinity (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
// Unable to convert -Infinity to Decimal.
// -Infinity (Single) --> -Infinity (Double)
Module 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 Infinity to Int64.
' Unable to convert Infinity to UInt64.
' Unable to convert Infinity to Decimal.
' Infinity (Single) --> Infinity (Double)
'
' Unable to convert -Infinity to Int64.
' Unable to convert -Infinity to UInt64.
' Unable to convert -Infinity to Decimal.
' -Infinity (Single) --> -Infinity (Double)
' The example displays the following output for conversions performed
' in an unchecked context:
' -3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
' -3.402823E+38 (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
' Unable to convert -3.402823E+38 to Decimal.
' -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
'
' -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
' -67890.13 (Single) --> 18446744073709483726 (0xFFFFFFFFFFFEF6CE) (UInt64)
' -67890.13 (Single) --> -67890.12 (Decimal)
' -67890.13 (Single) --> -67890.125 (Double)
'
' -12345.68 (Single) --> -12346 (0xFFFFFFFFFFFFCFC6) (Int64)
' -12345.68 (Single) --> 18446744073709539270 (0xFFFFFFFFFFFFCFC6) (UInt64)
' -12345.68 (Single) --> -12345.68 (Decimal)
' -12345.68 (Single) --> -12345.6787109375 (Double)
'
' 12345.68 (Single) --> 12346 (0x000000000000303A) (Int64)
' 12345.68 (Single) --> 12346 (0x000000000000303A) (UInt64)
' 12345.68 (Single) --> 12345.68 (Decimal)
' 12345.68 (Single) --> 12345.6787109375 (Double)
'
' 67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
' 67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
' 67890.13 (Single) --> 67890.12 (Decimal)
' 67890.13 (Single) --> 67890.125 (Double)
'
' 3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
' 3.402823E+38 (Single) --> 0 (0x0000000000000000) (UInt64)
' Unable to convert 3.402823E+38 to Decimal.
' 3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
'
' NaN (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
' NaN (Single) --> 0 (0x0000000000000000) (UInt64)
' Unable to convert NaN to Decimal.
' NaN (Single) --> NaN (Double)
'
' Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
' Infinity (Single) --> 0 (0x0000000000000000) (UInt64)
' Unable to convert Infinity to Decimal.
' Infinity (Single) --> Infinity (Double)
'
' -Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
' -Infinity (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
' Unable to convert -Infinity to Decimal.
' -Infinity (Single) --> -Infinity (Double)
숫자 형식의 변환에 대한 자세한 내용은 .NET 및 형식 변환 테이블의 형식 변환을 참조하세요.
부동 소수점 기능
구조체 및 관련 형식은 Single 다음과 같은 작업 범주를 수행하는 메서드를 제공합니다.
값 비교 메서드를 Equals 호출하여 두 값이 같은지 또는 메서드를 CompareTo 호출하여 두 Single 값 간의 관계를 확인할 수 있습니다.
구조체는 Single 전체 비교 연산자 집합도 지원합니다. 예를 들어 같음 또는 같지 않음을 테스트하거나 한 값이 다른 값보다 크거나 같은지 확인할 수 있습니다. 피연산자 중 하나가면 DoubleSingle 비교를 수행하기 전에 값이 a Double 로 변환됩니다. 피연산자 중 하나가 정수 형식인 경우 비교를 Single 수행하기 전에 변환됩니다. 이러한 변환은 확대되지만 정밀도 손실이 발생할 수 있습니다.
Warning
정밀도의 차이로 인해 같을 것으로 예상되는 두 Single 값이 같지 않은 것으로 판명되어 비교 결과에 영향을 줄 수 있습니다. 두 Single 값을 비교하는 방법에 대한 자세한 내용은 같음 테스트 섹션을 참조하세요.
, 및 IsPositiveInfinityIsNegativeInfinity 메서드를 IsNaNIsInfinity호출하여 이러한 특수 값을 테스트할 수도 있습니다.
수학 연산. 더하기, 빼기, 곱하기 및 나누기와 같은 일반적인 산술 연산은 메서드가 아닌 언어 컴파일러 및 CIL(공용 중간 언어) 명령에 의해 Single 구현됩니다. 수학 연산의 다른 피연산자는 연산 DoubleSingle 을 수행하기 전에 a Double 로 변환되고 연산의 결과도 값입니다Double. 다른 피연산자는 정수 계열 형식인 경우 연산을 수행하기 전에 변환 Single 되며 작업의 결과도 값입니다 Single .
클래스에서 (
Shared
Visual Basic에서) 메서드를 호출static
하여 다른 수학 연산을 System.Math 수행할 수 있습니다. 여기에는 산술(예: Math.Abs, Math.Sign및), 기하 도형(예: Math.Cos 및Math.Sin) 및 Math.Sqrt미적분(예: Math.Log)에 일반적으로 사용되는 추가 메서드가 포함됩니다. 모든 경우에 값은 Single .로 Double변환됩니다.값의 개별 비트를 조작할 수도 있습니다 Single . 메서드는 BitConverter.GetBytes(Single) 바이트 배열에서 비트 패턴을 반환합니다. 해당 바이트 배열을 메서드에 BitConverter.ToInt32 전달하면 값의 비트 패턴을 32비트 정수로 유지할 Single 수도 있습니다.
반올림. 반올림은 부동 소수점 표현과 정밀도 문제로 인한 값 간의 차이를 줄이는 기술로 자주 사용됩니다. 메서드를 Single 호출하여 값을 반올림할 Math.Round 수 있습니다. 그러나 메서드가 Single 호출되기 전에 값이 변환 Double 되고 변환에 정밀도 손실이 포함될 수 있습니다.
서식 지정 메서드를 Single 호출 ToString 하거나 복합 서식 지정 기능을 사용하여 값을 문자열 표현으로 변환할 수 있습니다. 서식 문자열이 부동 소수점 값의 문자열 표현을 제어하는 방법에 대한 자세한 내용은 표준 숫자 형식 문자열 및 사용자 지정 숫자 형식 문자열 항목을 참조하세요.
문자열 구문 분석 또는 TryParse 메서드를 호출 Parse 하여 부동 소수점 값의 문자열 표현을 값으로 Single 변환할 수 있습니다. 구문 분석 작업이 실패하면 메서드는 Parse 예외를 throw하는 반면 메서드는 예외를 TryParse 반환합니다
false
.형식 변환입니다. 이 구조는 Single 두 표준 .NET 데이터 형식 간의 변환을 지원하는 인터페이스에 대한 IConvertible 명시적 인터페이스 구현을 제공합니다. 언어 컴파일러는 값으로의 변환을 제외한 다른 모든 표준 숫자 형식에 대한 값의 DoubleSingle 암시적 변환도 지원합니다. 표준 숫자 형식 Double 의 값을 a Single 로 변환하는 것은 확대 변환이며 캐스팅 연산자 또는 변환 메서드를 사용할 필요가 없습니다.
그러나 32비트 및 64비트 정수 값의 변환에는 정밀도 손실이 포함될 수 있습니다. 다음 표에서는 32비트, 64비트 및 형식의 전체 자릿수 차이를 나열합니다 Double .
Type 최대 정밀도(10진수) 내부 전체 자릿수(10진수) Double 15 17 Int32 및 UInt32 10 10 Int64 및 UInt64 19 19 Single 7 9 정밀도 문제는 값으로 변환 Double 되는 값에 Single 가장 자주 영향을 줍니다. 다음 예제에서는 동일한 나누기 연산에서 생성되는 두 값이 같지 않습니다. 값 중 하나는 단 Double정밀도 부동 소수점 값이기 때문입니다.
using System; public class Example8 { public static void Main() { Double value1 = 1 / 3.0; Single sValue2 = 1 / 3.0f; Double value2 = (Double)sValue2; Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2)); } } // The example displays the following output: // 0.33333333333333331 = 0.3333333432674408: False
let value1 = 1. / 3. let sValue2 = 1f / 3f let value2 = double sValue2 printfn $"{value1:R} = {value2:R}: {value1.Equals value2}" // The example displays the following output: // 0.33333333333333331 = 0.3333333432674408: False
Module Example9 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
.NET
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기