Прочитай эту статью и переделай функцию, у меня выдает ошибки
Skip to main content
Stack Overflow
About
Products
OverflowAI
Log in
Sign up
Home
Questions
Tags
Users
Companies
LABS
Jobs
Discussions
COLLECTIVES
Communities for your favorite technologies. Explore all Collectives
TEAMS
Ask questions, find answers and collaborate at work with Stack Overflow for Teams.
Try Teams for free Explore Teams
Determine if a number can be precisely represented in float/double format
Ask Question
Asked 9 years, 9 months ago
Modified 9 years, 9 months ago
Viewed 11k times
19
How to determine if a number, for example 1.577, can be precisely represented in float or double format?
It means it is real 1.577 not a 1.566999999999994324 etc.
EDIT: I'm looking for a tool, where I can type a number and it will display double/float representation of it. So it's not only c# related question.
c#floating-point
Share
Improve this question
Follow
edited Feb 20, 2015 at 17:19
asked Feb 20, 2015 at 17:09
apocalypse's user avatar
apocalypse
5,8641010 gold badges4949 silver badges9696 bronze badges
3
In what format / type do you have the number? –
SLaks
Commented Feb 20, 2015 at 17:11
1
Do you have your number as a string? –
Sergey Kalinichenko
Commented Feb 20, 2015 at 17:12
Lets say i set double x = 1.000000001. I need function like this: IsEqual (x, "1.000000001"); –
apocalypse
Commented Feb 20, 2015 at 17:13
3
"I'm looking for a tool" - in that case, your question is an off-topic and will be closed. –
Ondrej Janacek
Commented Feb 20, 2015 at 17:20
1
To programmatically check if number can be represented precisely, you can look at: stackoverflow.com/questions/12097805/… –
RE6
Commented Feb 20, 2015 at 17:22
Show 6 more comments
3 Answers
Sorted by:
Не нашли ответ? Задайте вопрос на Stack Overflow на русском.
28
You can use an online decimal to floating-point converter. For example, type in 1.577 and you get two indications that it is not exact:
-
The "Inexact" box is checked
-
It converts to 1.5769999999999999573674358543939888477325439453125 in double precision floating-point.
Contrast that to a number like 1.25, which prints as 1.25, and the "Inexact" box is NOT checked.
(That converter can also check single-precision numbers.)
Share
Improve this answer
Follow
answered Feb 20, 2015 at 19:26
Rick Regan's user avatar
Rick Regan
3,5022323 silver badges2828 bronze badges
Whoever wrote that tool never learnt how to print floating point numbers. cs.indiana.edu/~dyb/pubs/FP-Printing-PLDI96.pdf –
leppie
Commented Feb 20, 2015 at 19:55
2
@leppie: I did. There is more than one algorithm that can print out a floating-point number correctly. –
tmyklebu
Commented Feb 20, 2015 at 20:25
4
@leppie: I don't think that's the point of the converter. It's aiming to show the exact value of the converted binary floating-point number (in decimal, amongst other possibilities) rather than the (usually) approximate value that Burger and Dybvig would give. Using Burger and Dybvig would be a bit pointless for the purpose of showing how a general value represented in decimal gets approximated when converting to binary. –
Mark Dickinson
Commented Feb 20, 2015 at 20:34
14
@leppie: Just to echo what Mark said, the main purpose of the converter is NOT to print a rounded value like Burger and Dybvig, Steele and White, or David Gay. That's what gets newbies in trouble. They enter 0.1 and the machine prints back 0.1. They they have no idea that internally, the value is not 0.1. That's why I wrote the tool. –
Rick Regan
Commented Feb 21, 2015 at 1:11
Add a comment
6
You already have answers on how to definitively check for exact representation. In addition, it is both feasible and useful to be able to eliminate many numbers without formally testing, and to check short decimal fractions on sight.
Suppose the decimal representation of your number terminates after N decimal places. For example, N is 3 for 1.577. Take the part after the decimal point, and look at it as in integer, 577. If the number is exactly representable as a binary fraction, that part has to be an integer multiple of 5^N. 577 is not an integer multiple of 125 so 1.577 is not exactly representable.
If you have a number of reasonable magnitude with only a few significant digits in its decimal representation, then if it passes this test it is exactly representable. For example, I know without computerized testing that 1.625 is exactly representable.
Share
Improve this answer
Follow
answered Feb 21, 2015 at 16:24
Patricia Shanahan's user avatar
Patricia Shanahan
26.2k44 gold badges4141 silver badges7575 bronze badges
Add a comment
1
Well, IEEE-754 double-precision has 53 bits of precision. The only numbers that can be represented exactly, then, are:
rational numbers,
with a terminating binary representation,
that is expressed in 53 bits or less
So...to figure out whether or not a given decimal value can be exactly represented, the following should suffice:
public bool IsExactlyRepresentableAsIeee754Double( decimal value )
{
// An IEEE 754 double has 53 bits of precision (52 bits of which are explicitly stored).
const decimal ieee754MaxBits = 0x001FFFFFFFFFFFFF ;
// move the decimal place right until the decimal's absolute value is integral
decimal n = Math.Abs(value) ;
while ( Decimal.Floor(n) != n )
{
n *= 10m;
}
bool isRepresentable = n <= ieee754MaxBits ;
return isRepresentable ;
}
There is a caveat, here, however: decimal tracks trailing, fractional zeros (for details see below), so 1m and 1.0m have different binary representations. So a round-trip like decimal x = (decimal)(double)1.00m ; will result in x having the same binary representation as 1m rather than that of 1.00m;
Since the internal representation of a decimal is well documented in the .Net CLR documentation and specs. Its backing store is readily available via the method Decimal.GetBits() and consists of 4 32-bit words, specified as follows:
The binary representation of a Decimal number consists of a 1-bit sign, a 96-bit integer number, and a scaling factor used to divide the integer number and specify what portion of it is a decimal fraction. The scaling factor is implicitly the number 10, raised to an exponent ranging from 0 to 28.
bits is a four-element long array of 32-bit signed integers.
bits [0], bits 1, and bits [2] contain the low, middle, and high 32 bits of the 96-bit integer number.
bits [3] contains the scale factor and sign, and consists of [the] following parts:
Bits 0 to 15, the lower word, are unused and must be zero.
Bits 16 to 23 must contain an exponent between 0 and 28, which indicates the power of 10 to divide the integer number.
Bits 24 to 30 are unused and must be zero.
Bit 31 contains the sign; 0 meaning positive, and 1 meaning negative.
A numeric value might have several possible binary representations; all are equally valid and numerically equivalent. Note that the bit representation differentiates between negative and positive zero. These values are treated as being equal in all operations.
So you probably could get clever and speed this up with a little bit twiddling. The kicker is that decimal tracks trailing zeroes so the binary representations of 1m and 1.00m differ — 1m is represented as +1 scaled by 100; 1.00m is represented as +100 scaled by 102. This complicates things a bit.
Share
Improve this answer
Follow
edited Feb 20, 2015 at 22:29
answered Feb 20, 2015 at 22:18
Nicholas Carey's user avatar
Nicholas Carey
73.9k1616 gold badges9595 silver badges136136 bronze badges
2
How is this supposed to work? It seems that your code will say that 0.1 is representable which is wrong. –
nwellnhof
Commented Feb 22, 2015 at 11:48
Add a comment
Your Answer
Sign up or log in
Sign up using Google
Sign up using Email and Password
Post as a guest
Name
Email
Required, but never shown
Post Your Answer
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Not the answer you're looking for? Browse other questions tagged c#floating-point or ask your own question.
The Overflow Blog
We'll Be In Touch - A New Podcast From Stack Overflow!
The app that fights for your data privacy rights
Featured on Meta
More network sites to see advertising test
We’re (finally!) going to the cloud!
Call for testers for an early access release of a Stack Overflow extension...
A proposal to stop curating/moderating Discussions until it's "fixed"
Linked
1
MIPS doesn't give exact value when doing mul.s
8
Is there a tool to know whether a value has an exact binary representation as a floating point variable?
3
How to check if number is divisible in c#?
0
How to determine w/o conversions that a given floating constant can be represented?
1
Incorect value for Float when using Json.toJson
Related
18
How to check if float can be exactly represented as an integer
10
Which values cannot be represented correctly by a double
1
How can I determine if a number entered by a user will be misrepresented when stored as a Single in C#?
3
How to check if a double can fit into a float without conversion to infinity
2
precision of Double and Decimal (in .NET)
1
What is the right way to check floating-point variables for exact value equality in c#?
0
Recognizing floating point in double variable
1
Guaranteed precision with numerics?
7
How to determine whether number is exactly representable in floating-point?
0
Test whether a decimal value can be converted to double
Hot Network Questions
I'd like to change a single color in an image texture
Best way to design a PCB for frequent component switching?
"Your move, bud."
Did Jacques Charles first attempt to use the Celsius scale in his gas law?
Safety concerns with this Antenna in close proximity?
How complex is the God of Classical Theism?
Interpreting a constraint on a simplified static spherically symmetric metric
Girls and boys parades
Can I in Coq define a class with a notation for its field such that another field uses the notation?
Are there three distinct Pythagorean triples on six integers?
US jurisdictions
Conflict between fontspec and libertinust1math
Precison of InterpolatingFunction decreases to MachinePrecision in ParallelTable
Is it a bad idea to talk about the city/country in phd application letters?
Sci-fi movie that starts with a man digging his way out of a crashed spacecraft and promptly being torn in half
Why does the special character ? need to be escaped in grep, but not . or *?
Can I use a red tablecloth for Shabbos?
Why is the lower cost gained by cheap illegal immigrant labour used as an argument in America?
Could you make a quadcopter who’s propellers can also work as wheels?
Is it allowed to use web APIs exposed in open-source code?
I think my professor didn't grade me properly. Can you help me? Two questions about propositional logic formalisation
Why does one of my GAM responses not fit the data well?
What's the translation of "stand-up meeting" in French?
Steampunk book about a female lead who lives on an island and works in a volcano
Question feed
STACK OVERFLOW
Questions
Help
Chat
PRODUCTS
Teams
Advertising
Talent
COMPANY
About
Press
Work Here
Legal
Privacy Policy
Terms of Service
Contact Us
Cookie Settings
Cookie Policy
STACK EXCHANGE NETWORK
Technology
Culture & recreation
Life & arts
Science
Professional
Business
API
Data
Blog
Facebook
Twitter
LinkedIn
Instagram
Site design / logo © 2024 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2024.11.21.19097