Count how long the floating point is - java

How can I count how long the floating point is?
e.g.
count(10.123); //result: 3
count(10); //result: 0
count(10.3771) //result: 4
I know how to count it when transforming to a string, but that isn't very efficient, is it?

A double is always a specific length. It will only show the numbers need to obtain the accuracy.
ie. 10.3771 is the equivilant to 00000010.37710000 (not the exact number of 0's that are really there, I'm just trying to explain the concept).
In reality even this is inaccurate as a double is a 64 bit binary number
Converting it to String is your best bet and not an inefficient method.

Related

Get nth digit after decimal point

What would be the most efficient way to grab the, say, 207th decimal place of a number? Would it just be x * Math.pow(10,207) % 10?
How's this for python
int((x*(10**n)))%10
What you want is impossible.
The only things in java that work with Math.pow and basic operators are the primitives. The only floating point primitives are float and double. These are IEEE754 floating point numbers; doubles are 64 bits and floats are 32 bits.
A simple principle applies: If you have 64 bits, then you can only represent 2^64 different numbers (it's actually a little less). So, you get about 18446744073709551616 numbers, of all numbers in existence, which actually exist as far as the computer is concerned for doubles. all other numbers do not exist.
So what happens if a mathematical operation (say, 0.1 + 0.2) ends up being a number that doesn't exist? Well, java (this is predicated by the IEEE754 standard; most languages and chips do it this way) will return you the nearest number amongst all the 18446744073709551616 numbers that do exist.
The problem with wanting the 207th digit is that obviously, given that only 18446744073709551616 numbers exist, none of those 18446744073709551616 numbers have that kind of precision. Asking for the 207th digit is therefore completely random. It says nothing about the input number... whatsoever.
Let me repeat that: There are no double values that have a significant 207th digit AT ALL.
If you want 'perfect' representation, with no rounding whatsoever, you want BigDecimal, but note that demanding perfection is tricky. Imagine in basic decimal math (computers are binary, but lets stick with decimal as we're all much more familiar with it, what with our 10 fingers and all), I ask you to only give me perfect answers, and then I ask you to divide 1 by 3.
BigDecimal won't let you do that either, so the ops you can run on BigDecimals without telling BigDecimal in what ways it is allowed to be inprecise leads to exceptions.
If you've set it all up exactly how you wanted it, and you really have a BigDecimal with a 207th digit after the comma, you can use the scale feature, or just the power-of-10 feature to get what you want.
Note BigDecimal is not primitive and therefore does not support the +, %, etc operators.
***Special Note: There is no: "This will handle all situations" answer here as the arbitrary value such as 207 could take the calculations way outside the bounds of possible precision of the variable types involved. My answer as such will only work within the bounds of variable type precision for which 207 is really not possible...
To get the specific digit an arbitrary number (like 207) of places after the decimal point... if you just multiply by factor of 10.. and then take mod 10, the answer (in java) is still a floating point type... not a single digit...
To get a specific digit an arbitrary number (n) of places after the decimal point, without converting to string:
Math.floor(x*Math.pow(10,n)) % 10;
to get 4th digit after 2.987654321
x*Math.pow(10, 4) = 29876.54321
Math.floor(29876.54321) = 29876
29876 % 10 = 6

Can someone explain the Math.ulp(double) method?

I haven't been able to find any information online that doesn't already assume I know things. I wonder if anyone knows any good resources that I can look into to help me wrap my head around what this function does exactly?
From what I gather, and I'm pretty certain this is wrong or at least not fully right, is that given a floating point, it determines the distance between itself and some number next in a sequence? There appears to be something to do with how number are represented bitwise, but the sources I've read never explicitly said anything about that.
http://matlabgeeks.com/tips-tutorials/floating-point-comparisons-in-matlab/
illustrated it rather well:
float2bin(A)
//ans = 0011111110111001100110011001100110011001100110011001100110100000
float2bin(B)
//ans = 0011111110111001100110011001100110011001100110011001100110011010
You can see the difference in precision at a binary level in this example. A and B differ by 6 ulps (units in the last place)
I believe that it is showing the distance between the number you specify, and the next largest binary float that can be encoded.
Because of the range that binary floating point numbers cover and their precision, not all numbers between any two given real numbers are covered, so it looks like this is giving you the positive distance between the number you wish to encode and the actual number it would be stored as.
From Wikipedia:
the unit of least precision (ULP) is the spacing between floating-point numbers, i.e., the value the least significant digit represents if it is 1

Why does for loop using a double fail to terminate

I'm looking through old exam questions (currently first year of uni.) and I'm wondering if someone could explain a bit more thoroughly why the following for loop does not end when it is supposed to. Why does this happen? I understand that it skips 100.0 because of a rounding-error or something, but why?
for(double i = 0.0; i != 100; i = i +0.1){
System.out.println(i);
}
The number 0.1 cannot be exactly represented in binary, much like 1/3 cannot be exactly represented in decimal, as such you cannot guarantee that:
0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1==1
This is because in binary:
0.1=(binary)0.00011001100110011001100110011001....... forever
However a double cannot contain an infinite precision and so, just as we approximate 1/3 to 0.3333333 so must the binary representation approximate 0.1.
Expanded decimal analogy
In decimal you may find that
1/3+1/3+1/3
=0.333+0.333+0.333
=0.999
This is exactly the same problem. It should not be seen as a weakness of floating point numbers as our own decimal system has the same difficulties (but for different numbers, someone with a base-3 system would find it strange that we struggled to represent 1/3). It is however an issue to be aware of.
Demo
A live demo provided by Andrea Ligios shows these errors building up.
Computers (at least current ones) works with binary data. Moreover, there is a length limitation for computers to process in their arithmetic logic units (i.e. 32bits, 64bits etc).
Representing integers in binary form is simple on the contrary we cant say the same thing for floating points.
As shown above there is a special way of representing floating points according to IEEE-754 which is also accepted as defacto by processor producers and software guys that's why it is important for everyone to know about it.
If we look at the maximum value of a double in java (Double.MAX_VALUE) is 1.7976931348623157E308 (>10^307). only with 64 bits, huge numbers could be represented however problem is the precision.
As '==' and '!=' operators compare numbers bitwise, in your case 0.1+0.1+0.1 is not equal to 0.3 in terms of bits they are represented.
As a conclusion, to fit huge floating point numbers in a few bits clever engineers decided to sacrifice precision. If you are working on floating points you shouldn't use '==' or '!=' unless you are sure what you are doing.
As a general rule, never use double to iterate with due to rounding errors (0.1 may look nice when written in base 10, but try writing it in base 2—which is what double uses). What you should do is use a plain int variable to iterate and calculate the double from it.
for (int i = 0; i < 1000; i++)
System.out.println(i/10.0);
First of all, I'm going to explain some things about doubles. This will actually take place in base ten for ease of understanding.
Take the value one-third and try to express it in base ten. You get 0.3333333333333.... Let's say we need to round it to 4 places. We get 0.3333. Now, let's add another 1/3. We get 0.6666333333333.... which rounds to 0.6666. Let's add another 1/3. We get 0.9999, not 1.
The same thing happens with base two and one-tenth. Since you're going by 0.110 and 0.110 is a repeating binary value(like 0.1666666... in base ten), you'll have just enough error to miss one hundred when you do get there.
1/2 can be represented in base ten just fine, and 1/5 can as well. This is because the prime factors of the denominator are a subset of the factors of the base. This is not the case for one third in base ten or one tenth in base two.
It should be for(double a = 0.0; a < 100.0; a = a + 0.01)
Try and see if this works instead

How to do arithmetic operations in binary with Java?

For a Java assignment I am required to be able to pass any number that will be introduced as a string through the command line (no matter how big) into binary.
Then generate methods that will allow these numbers to add, multiply, subtract and divide.
My question would be first:
How do I make my string into binary
Eg:
123 would become 1111011
8403678 would become 100000000011101011011110
And so forth...
Then the biggest issue is to get them to add up, subtract each other, etc.
Last I need to be able to convert back the result from binary back to decimal which I am having more trouble understanding how to do it than the previous case (transforming from binary into a decimal string).
Eg:
if 1111011 was added to 100000000011101011011110 the result would be 100000000011101101011001 and then it would become 8403801 which I would print out as a result.
The final aim of this project is to create our own class such as java.math.BigInteger (without using it of course) and handling arbitrarily big numbers (bigger than what Int can handle).
If there is any extra information required please let me know I will answer promptly.
Since you have to be able to handle large numbers without using BigInteger, you need to find a way to represent arbitrarily large numbers. Obviously int will not do. One easy way is to represent the number as a String. For instance, the number 123 could be stored as the String "123".
Converting to binary will require some intermediate operations such as division and modulo. Thus, it is worth thinking about how to do these when your numbers are stored in Strings. Since this is homework I don't want to just give you the answer, but some guidance instead.
Say you want to do addition.
Think about how you add big numbers by hand. Which digits of each number do you use, and how do you manipulate them to get the answer? This algorithm is fairly straightforward, and once you can explain it, you can give a computer directions to do it as well. (For addition, you add first the one's digits, then the ten's digits, etc... and remember to carry if you have to!)
Note that you can get the digits of your number String by using a method such as charAt(int n). This will return the character at index n of the string. Convert it to an Integer by using Integer.parseInt() (which takes a numeric string and converts it to an integer).
So now you can think: If I want the one's digit of a number, what index would that be in a String? Starting with this, you should be able to figure out how to get any digit you want from a big number string. Now, you can implement your algorithm.
Finally, to convert from base ten to binary you do need to understand how number bases work. This gives a clear and quick introduction: http://www.math.grin.edu/~rebelsky/Courses/152/97F/Readings/student-binary
The section "Converting from decimal to binary" in the above link describes a method for exactly what you want to do. Good luck.

Why do floats seem to add incorrectly in Java? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Is JavaScript's Math broken?
Java floating point arithmetic
I have the current code
for(double j = .01; j <= .17; j+=.01){
System.out.println(j);
}
the output is:
0.01
0.02
0.03
0.04
0.05
0.060000000000000005
0.07
0.08
0.09
0.09999999999999999
0.10999999999999999
0.11999999999999998
0.12999999999999998
0.13999999999999999
0.15
0.16
0.17
Can someone explain why this is happening? How do you fix this? Besides writing a rounding function?
Floats are an approximation of the actual number in Java, due to the way they're stored. If you need exact values, use a BigDecimal instead.
They are working correctly. Some decimal values are not representable exactly in binary floating point and get rounded to the closest value. See my answer to this question for more detail. The question was asked about Perl, but the answer applies equally to Java since it's a limitation of ALL floating point representations that do not have infinite precision (i.e. all of them).
As suggested by #Kaleb Brasee go and use BigDecimal's when accuracy is a must. Here is a link to a nice explanation of tiny details related to using floating point operations in Java http://firstclassthoughts.co.uk/java/traps/java_double_traps.html
There is also a link to issues involved with using BigDecimal's. Highly recommended to read them both. It really helped me.
Enjoy, Boro.
We humans are used to think in 'base 10' when we deal with floating point numbers 'by hand' (that is, literally when writing them on paper or when entering them into a computer). Because of this, it is possible for us to write down an exact representation of, say, 17%. We just write 0.17 (or 1.7E-1 etc). Trying to represent such a trivial thing as a third can not be done exactly with that system, because we have to write 0.3333333... with an infinite number of 3s, which is impossible.
Computers dealing with floating point not only have a limited number of bits to represent the mantissa (or significand) of the number, they are also restricted to express the mantissa in the base of two. That means that most percentages (which we humans with our base 10 floating point convention always can write exactly, like for example '0.17') are impossible for the computer to store exactly. Fractions like 0%, 25%, 50%, 75% and 100% can be expressed exactly as a floating point number in a computer, because it consists of either halves (2E-1) or quarters (2E-4) which fits nicely with a digital representation of a number. Percentage values like 17% or even trivial ones (for us humans!!) like 10% or 1% are as impossible for computers to store exactly simply because those numbers are, for the binary floating point system what the 'one third' is for the human (base 10) floating point system.
But if you carefully pick your floating point values, so they always are made of a whole number of 1/2^n where n might be 10 (meaning an integer number of 1/1024), then they can always be stored exactly without errors as a floating point number. So if you try to store 17/1024 in a computer, it will go smoothly. You can actually store it without error even using the 'human base 10' decimal system (but you would go nuts by the number of actual digits you have to deal with).
This is some reason I believe why some games express angles in a unit where a whole 360 degree turn is 256 angle units. Can be expressed without loss as a floating point number between 0 and 1 (where 1 means you go a full revolution).
It's normal in double representation on the computer. You lose some bits then you will have such results. Better solution is to do this:
for(int j = 1; j <= 17; j++){
System.out.println(j/100.0);
}
This is because floating point values are inherently not the same as reals in the mathematical sense.
In a computer, there is only a fixed number of bits that can be used to represent value. This means there are a finite number of values that it can hold. But there are an infinite amount of real numbers, thus not all of them can be represented exactly. But usually the value is something close. You can find a more detailed explanation here.
That is because of the limitations of IEEE754 the binary format to get the most out of 32 bit.
As others have pointed out, only numbers that are combinations of powers of two are exactly representable in (bianary) floating point format
If you need to store arbitrary numbers with arbitrary precision, then use BigDecimal.
If the problem is just a display issue, then you can get round this in how you display the number. For example:
String.format("%.2f", n)
will format the number to 2 decimal places.

Categories

Resources