Casting of long to float

Hello Friends,
While preparing for A JAVA test, i came across a strange behavior in java language. will be greatful if somebody can clarify it.
The problem is:
if we try to assign long data type to int without casting explicitly, complier will throw an error, e.g. consider the following piece of code-
int iData2=10000000000000L;
The compiler will say that there is a possible loss of precision.
but if i replace int by float e.g. change the above code to
float fData2=10000000000000L;
the compiler is accepting code without giving any warning that there is a possible loss of precision, although there is such a loss in the output.
is this behaviour justified?

you have to draw the line somewhere... so Java just
looks at the range of numbers that can be presented;
for every long there is a float that is fairly close to it.Okay, but the difference between some long values that have been converted to a float are not close at all. For example:
     long l = (long)Math.pow(2,63) - 1000000000000L;
     float f = l;
     long l2 = (long)f;
     System.out.println("l is:" + l);
     System.out.println("l2 is:" + l2);
     System.out.println("l-l2 is:" + (l-l2));
The output is:
l is:9223371036854775807
l2 is:9223370937343148032
l-l2 is:99511627775
I don't call a difference of 99511627775 close. I think you should have to cast a long to a float.
-- MWR
you can't have the compiler complain about
everything, otherwise you woldn't be able to do
anything useful...
for example:
double d = 0.1; // 1
float f = 1;
f = f/10; // 2
double d = d - f; // 3
on line 1: possible loss of precision becausethere
is no double that represents one tenth exactlyCould not really get it. where is the chance ofloss
of precision? In Java, floating point literals areby
default double type. So if u assign double to a
double , there is no chance of loss of precision.By
the way, i executed this code. Compiler didnot
complain and output was "d=0.1"
on line 2: possible loss of precision because
the
result of dividing by a non-power of two cannotbe
represented exactly as a floating point numberhere also, there is no chance of loss ofprecision.
because u r assigning an int literal(32 bit) to a
float variable (also 32 bit).
on line 3: possible loss of precision because
you
subtract near-equal values from each other,producing
a massive relative errorthis is ok.. it will give loss of precision with
compiler complaints. :-)
you have to draw the line somewhere... so Javajust
looks at the range of numbers that can bepresented;
for every long there is a float that is fairlyclose
to it.
srry one rectification..
*this is ok.. it will give loss of precision
without
compiler complaints. :-)

Similar Messages

  • Double - Float casting or Why isn't there float sqrt?

    Is there any reason why not to include float sqrt? I'm pretty pissed since, it is just... well plain stupid. I hope it can be added, not to mention that casting takes away performance, not much, but I have to do a lot of casting since I'm doing 3d grahpics... Anyone know any solluions? Is there any point going the hard way and implementing own sqrt for float?
    WHY WHY WHY, OH WHY.
    Something is rotten in the state of java.

    The absence of Math.sqrt(float) and float versions of other relevant methods is apparently becuase early versions of the Java compiler could not distinguish overloaded methods which only differed in double/float parameters. The current compilers do not have this problem and it has been proposed that the extra methods should be added but I don't know when this might happen.
    In any case how sure are you that casting between double and float is causing any significant performance problem? This cast is NOT particularly expensive (casting to 'int' from float or double is usually much more expensive).
    What processor are you using --- as far as I know Intel processors do not give any speed benefit from doing sqrt on float instead of double. I believe that many RISC processors do benefit from using float where possible.

  • Java Types Conversting & Casting .

    Hi All !
    Really i do have two questions regarding Java Type Conversion and Casting
    and hope i would find (good) answers :
    [Q1:]
    why it's legal to convert(implicitly) from ( long --> float ) and this is
    said to be a widening conversion even if the size of long is longer than float
    and hence there a possible loss of information ?
    [Q2:]
    why it's legal to cast(explicitly) from ( byte --> char ) and how compiler will deal
    with byte as singed and char as unsigned during type casting (this is said to be
    a narrowing converstion and it is really is ) ?
    for [Q2:] i did the follwing code :
    public class TestNarw
         public TestNarw()
              byte bBefore=-100; // change this value to whatever negative number that is to fit in a byte.
              char c=(char)bBefore;
              byte bAfter=(byte)c;
              System.out.println(bBefore);
              System.out.println(c);
              System.out.println(bAfter);
         public static void main(String args[])
              new TestNarw();
               the SURPRISE on the code above is that the output is :
    -100
    -100
    and when i change the value of "bBefore" to any negative number that is to fit in a
    byte it (e.g: -10) it gives the same value for the variable "c" (character)which is ASCII "63" ="?"
    but when i test it with a suitable postive number , it works fine and the character (c) represents that number
    so how it deals with converstion from negative byte to char ?
    Thanks ...

    Q1: you can always cast between primitive types (numbers, not boolean). The only problem is you lose precision in certain directions. A long to float isn't necessarily going to change the value, but it really depends on the long value. If it's out of range of float, it'll basically be wrapped around to the negative side. (at least that's what long to int would do, not sure if float or double behave different in that regard).
    Q2: The value -100 converted to a char would probably be 65436, which prints as "?" because DOS can't print that character. Then when you cast back, 65436 is out of range for a byte, so it rolls back around to -100.
    Try this:
    byte b = 127;
    System.out.println(b);
    System.out.println((byte)b+1);
    System.out.println((byte)0xFF); // 255 in hex
    It'll print 127, then -128, then -1. When you go out of range, it just wraps around. For this reason, you often have to be carefull what size you store things as.

  • What's casting for?

    I've seen some codes have the type in parenthesis then the value... like:
    (long) Math.random()*1000What's that do?

    The promotion from an int to a long, float, or double
    (for example) can be done without a cast.
    int i = 123;
    double d = i; // all three of these are okay w/o cast ...
    long el = i; // no precision will be lost ... "widening conversions"
    float f = i;
    The de-promotion (is that even a word?) of a double to a
    float, long, or int can not be done without a cast. These
    go "against the flow" of direction of Fred's sequence of types.
    double d = 123.45D;
    int i = (int) d; .. cast is required for these "narrowing conversions"
    long el = (long) d;
    float f = (float) d;
    Why would you do this stuff ? As alluded to in an earlier post,
    adding two integers is not guaranteed to result in an integer -
    it could overflow. Assigning the result to a long will alleviate
    the problem.
    Or, say you have a long and you know its a "small" (ie, int sized)
    long ... and you want to pass it to a method the requires an int
    parameter ... a cast would accomplish this ...
    boolean doSomethingRequiringAnInt( (int) aLongValue );
    Hope this helps a little ...
    Eric

  • Will I lose data converting from double-pre​cision to single-pre​cision float?

    Before you say yes... 
    I am using a crio device in scan-mode interface. The values that the scan mode returns are in double-precision floating point. Apparently I am supposed to be able to choose between double-precision floating point ("calibrated") and fixed-point ("uncalibrated") data, but this functionality appears to be exclusive to the fpga interface and is not available with the scan engine. Both data types are 64-bits per value, so when it comes to size-on-disk, either way is basically the same anyways.
    The system is continuously recording 13 channels of double-precision floating point at 200Hz. Using the binary file write method, I have measured this to be about 92 MB/hr to disk. (over 120mb/hr with tdms and a lot more for write to spreadsheet) Simply put, this 92 mb/hr rate is just too much data to disk on this system. 
    The modules I am recording from, the 9236, 9237, and 9215 c-series modules, have 24-bit ADCs or less. Does this mean I don't need 64 bits to represent the number and maintain the same accuracy?
    Can I coerce/cast the double-precision floating point values I am receiving from the scan engine i/o variables to another, smaller data type like single-precision floating point and still maintain the same accuracy?
    Message Edited by rex1030 on 08-27-2009 04:19 PM
    [will work for kudos]
    Solved!
    Go to Solution.

    For some reason the scan interface isnt letting me output the raw U32 values. I think it might have something to do with the fact that I am using both scan engine and fpga interfaces in the project, but I am not sure. Any ideas why this is happening?
    This is a picture of me right mouse clicking on one of the modules to try to get it to put out raw U32 values like this knowledgebase article says I can.
    I put in a service request.. (Reference#7256901) because to be honest I have to know for sure whats going on. I am not one of the engineers/scientists that designed the experiment so I cannot say whether it is ok to chop some of the end of the number off. I would rather simply be able to record all the data in a smaller amount of disk space then go tell them we have to compromise somewhere, whether on sample rate or precision. 
    [will work for kudos]

  • How to cast this?

    Hi Folks!
    I am new in java and trying to cast a long in integer. I am not sure what?s wrong in my code?
    Can anybody tell me what?s wrong and how should I get it correct?
    Here is my code.
      Integer a1,b1;
      Stack st = new Stack();
        a1 = (Integer)st.pop();
        b1 = (Integer)st.pop();
        long x;
        x=(long)a1;
        sdos.writeLong(x);
        dos.flush();Thanks a lot in Advance.

    x = a1.longValue();http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Integer.html#longValue()

  • How to change long - int ?

    i have a retrieved a long " long koko = files.length(); " witch i need to represent in integer for "fis.read(id3test, koko, 20);" if someone could help me i would really be glad.... ... thanks in advance.

    well, you can simply cast it
    long thelong = 123456;
    int a = (int)thelong;
    But in this way you will loose the half of the bytes, so if the long value is bigger than Integer.MAX_VALUE, you will have perhaps strange or unwanted results, so be patient.

  • Casting Object into primitive

    I'm using java reflection to return value of an attribute from a Class. The attribute is a float primitive. However, the return form is an Object. How do I cast it into the float primitive again?
    Thanks.
    LG

    From the API for Method.invoke: >>if the value has a primitive type, it is first appropriately wrapped in an object<<
    So if the method returns a float primitive, Method.invoke will return a Float object.

  • Typecasting ..... Long to double

    can any body tell me how to convert a long variable into double ....i am writing code of a scientific calculator in java.... and i need help in factorial function to convert a long into double .....
    i will be grateful .............. thanks

    double theDouble = (double)theLong;You don't need a cast from long to double?I thought you'd need to, but my compiler didn't complain, so I guess not.
    double theDouble = theLong;

  • Float - double == loss of accuracy?  why?

    The following test fails:
    public void testFloat() {
            float number = 46702.45F;
            Float numberAsFloat = new Float(number);
            double numberAsDouble = numberAsFloat.doubleValue();
            System.out.println(numberAsDouble);
            assertTrue(46702.45 == numberAsDouble);
    }I probably just don't understand floating point data types or something, but I was very surprised that this test fails. If someone could enlighten me on WHY this fails, I would really appreciate it. For what it's worth, the value printed out for numberAsDouble was 46702.44921875 which I find entirely unexpected considering I am going from a lower precision data type (float) to a higher precision data type (double).

    Remember: the floating point representations (float and double) store binary values. Not decimal. The decimal values are parsed by the compiler and turned into floats and doubles in binary.
    The said binary values are approximations to the decimal values. Sometimes the binary and the decimal values coincide, but some times they don't.
    Floats have less precision than doubles.
    The binary string that represents that number, in a float, will be interpreted differently in a double, because the double has those additional bits of precision.
    Consider this code:
        double nd = 46702.45d;
        float nf = 46702.45F;
        long ndl = Double.doubleToLongBits(nd);
        long nfl = Float.floatToIntBits(nf);
        long nfl2 = Double.doubleToLongBits(nf);
        System.out.println(Long.toBinaryString(ndl));
        System.out.println(Long.toBinaryString(nfl));
        System.out.println(Long.toBinaryString(nfl2));It prints this:
    100000011100110110011011100111001100110011001100110011001100110
    1000111001101100110111001110011
    100000011100110110011011100111001100000000000000000000000000000
    // now I add spaces to line up the various segments
    // sign   exponent  mantissa
         1 00000011100  110110011011100111001100110011001100110011001100110
         1    00011100  1101100110111001110011
         1 00000011100  110110011011100111001100000000000000000000000000000Look at that string of "0011"'s on the version of the number created as a double.
    Compare it to the 0's in the version that was created as a float and used as a double.

  • Casting byte [] into int

    I have a typcal problem.
    I have two bytes array and i wantto cast that into int type and have four byte array which i have to cast into long.
    can anyone help me..
    thanks in advance
    Sai Burra

    public int toInt(byte[] bytes) {
        return (bytes[0] << 8) | bytes[1];
    }Note this actually returns a short, since a Java int is a 32-bit number, and this returns 16 bits worth of number.
    There's no way to directly cast a non-primitive type (an array) to a primitive type (an int).

  • Casting one type to another type

    For this block statement:
           public static String methodEx(MyClass  objRef)
               if (objRef  !=  null)
                  StringBuffer dat = new StringBuffer();
                  for(int i=0;i < 40;i++)
                         dat.append( "myData" + i );
           return dat.toString();
           }I assume this line: return dat.toString();
    is casting the StringBuffer object reference (dat) to a String object reference?

    I assume this line: return dat.toString();
    is casting the StringBuffer object reference
    (dat) to a String object reference?Nope. Casting is when you don't really change the data, but rather you change the name of the "box" that its in. For instance the code below casts a long variable as an int:
       long longVar = 500L;
       int intVar = (int)longVar;toString is a method that takes the StringBuffer data, and changes it to something completely different, a String, and no casting is involved. Another way that I look at it, casting is almost a passive process while the toString method above is an active process.

  • Float/double confusion

    Could someone explain the theory behind the following:
    The default floating point data type is a double, hence the following declaration will not compile:
    float f=1.3;
    However the following declaration will compile:
    float f=1/3
    ...without specifying that it should be a float. Why does this happen, and why is the resulting value in f 0.0? Surely it should be 0.3333 or similar?

    1/3 is the integer 1 divided with the integer 3, and since they both are integers it would be natural for the result to be integer too, and so the division performed is called integer division. And the integer 0 is the result because one third is doesn't fit any integer. The fractional part is clamped. This result is then implicitely casted to produce the float 0.0f.
    Why? Because that's the way it goes in C and C++.

  • Widening conversion bugs ?

    I dont understand .. (from A Programmer's Guide to Java Certification 3rd Edition - mughal pg 172)
    a) this work
    Integer iRef3 = (short)10; // constant in range: casting by narrowing to short,
    // widening to int, then boxing
    b) final short x = 3;
    Integer y = x;
    this work but not this.
    short x = 3;
    Integer y = x;
    The 'final' means constant expression which is used for implicit narrowing conversion. The 2nd one is not narrowing conversion so why the 2nd one didnt work?
    c) Exactly as a) but instead of Integer .. i use Long. // This doesnt work
    Long iRef3 = (short)10;
    c) This also doesnt work unless i put the final on short
    short s = 10; // narrowing (a)
    Integer iRef1 = s; // short not assignable to Integer -- error here (b)
    Since implicit conversion succeded for (a) and you dont need constant expression for widening conversion (b) .. why it doesnt work on (b).
    I thought the variable s would be widen to int and then boxing into Integer.
    Any help is appreciated
    Edited by: yapkm01 on Jul 16, 2009 9:32 PM

    A type conversion from long to float is
    commonly called a widening conversion and thus legal.
    I understand that the range of float variables
    is wider than that of long variables.
    However, a long variable can hold about 4
    billion (2^64) distinct integer values. How could
    these possibly all be represented by a float
    variable that uses only 32 bits - and thus can only
    represent 2^32 distinct values. The mantissa of a
    float variable actually uses even less bits -
    only 23.
    So, while any value of a long variable will
    fall within the range of a float variable,
    occasionally approximation should occur and
    information get lost.
    Why is then usually said that widening conversion
    doesn't lose information?Mathematically, a float's bigger. You do lose precision, though.
    What's your point?

  • Money calculation using Java

    Hi,
    I have problem with calculating the total amounts. I am not sure what's wrong with the below code snippet, could anyone help me please.
    If the value of authDoubleAmount in line 3 of code below is 34.8, by casting to long it returns 3479. I am loosing the precession of value 01 after the decimal point. How do I get 3480 instead of 3479.
    BigDecimal authBigDecimalAmount =authMoneyAmount.getRoundedValue(2, BigDecimal.ROUND_HALF_DOWN);
    double authDoubleAmount = authBigDecimalAmount.doubleValue();
    long authLongAmount = (long) (authDoubleAmount * 100);
    Thanks

    If you are working with money, you SHOULD NEVER use float or double, for they represent numbers in a non continuous way (there are numbers lacking, that they cannot hold) , you should work with them through the BigDecimal mehtods.
    May the code be with you.

Maybe you are looking for