Float / NAN

Hi,
I have a simple sql spatial query which returns a float. (the distance between 2 points)
however, in some instances the answer returned should be null.
Unfortunately the in the cases where null or NAN should be the answer, I get 0.0.
(The code is below.)
Is there a problem with null values/float values using OJDBC?
Any suggestions on how to get around this?
Thanks,
Eoin.
The code I am using to extract the result is:
while(ors1.next()){
distance = ors1.getFloat(1);
if(distance==0.0){
System.out.println("caution: Distance returned is 0.0");
}

This is basic Java. A float is a light-weight object, which can't be
null. Either do a getObject() (which will return a Number type, or null),
or call wasNull() to detect whether the last 0.0 returned would
have been a null if it were possible. I would drop floats entirely
and use BigDecimals so you never lose accuracy.
Joe Weinstein at BEA Systems

Similar Messages

  • Float.NaN doesn't seem to work with appserver7

    I am in the process of upgrading an existing application that uses Float.NaN for invalid values when persisting to the database. I am upgrading from just using SQL statements to entity beans for the persistence layer. Is Float.NaN or Double.NaN not supported in EJB2.0 in appserver 7? The error message I get is that it is column 'NaN' does not exist.

    Here is the descriptor in ejb-jar:
    <entity>
    <display-name>Attribute</display-name>
    <ejb-name>Attribute</ejb-name>
    <local-home>com.dataservices.common.ejb.entity.attribute.AttributeLocalHomeIF</local-home>
    <local>com.dataservices.common.ejb.entity.attribute.AttributeLocalIF</local>
    <ejb-class>com.dataservices.common.ejb.entity.attribute.AttributeBean</ejb-class>
    <persistence-type>Container</persistence-type>
    <prim-key-class>com.dataservices.common.ejb.entity.attribute.AttributeKey</prim-key-class>
    <reentrant>False</reentrant>
    <abstract-schema-name>Attribute</abstract-schema-name>
    <cmp-field>
    <field-name>id</field-name>
    </cmp-field>
    <cmp-field>
    <field-name>resultId</field-name>
    </cmp-field>
    <cmp-field>
    <field-name>x</field-name>
    </cmp-field>
    <cmp-field>
    <field-name>y</field-name>
    </cmp-field>
    <cmp-field>
    <field-name>z</field-name>
    </cmp-field>
    <cmp-field>
    <field-name>comments</field-name>
    </cmp-field>
    <query>
    <query-method>
    <method-name>find</method-name>
    <method-params>
    <method-param>int</method-param>
    </method-params>
    </query-method>
    <ejb-ql>SELECT OBJECT (attribute) FROM Attribute AS attribute WHERE attribute.id = ?1</ejb-ql>
    </query>
    <query>
    <query-method>
    <method-name>findByIdAndResultId</method-name>
    <method-params>
    <method-param>int</method-param>
    <method-param>int</method-param>
    </method-params>
    </query-method>
    <ejb-ql>SELECT OBJECT (attribute) FROM Attribute AS attribute WHERE attribute.id = ?1 AND attribute.resultId = ?2</ejb-ql>
    </query>
    <query>
    <query-method>
    <method-name>findAllByResultId</method-name>
    <method-params>
    <method-param>int</method-param>
    </method-params>
    </query-method>
    <ejb-ql>SELECT OBJECT (attribute) FROM Attribute AS attribute WHERE attribute.resultId = ?1</ejb-ql>
    </query>
    </entity>
    Here is sun-cmp-mapping:
    <entity-mapping>
    <ejb-name>Attribute</ejb-name>
    <table-name>Attribute</table-name>
    <cmp-field-mapping>
    <field-name>x</field-name>
    <column-name>Attribute.x</column-name>
    </cmp-field-mapping>
    <cmp-field-mapping>
    <field-name>comments</field-name>
    <column-name>Attribute.comments</column-name>
    </cmp-field-mapping>
    <cmp-field-mapping>
    <field-name>y</field-name>
    <column-name>Attribute.y</column-name>
    </cmp-field-mapping>
    <cmp-field-mapping>
    <field-name>z</field-name>
    <column-name>Attribute.z</column-name>
    </cmp-field-mapping>
    <cmp-field-mapping>
    <field-name>id</field-name>
    <column-name>Attribute.id</column-name>
    </cmp-field-mapping>
    <cmp-field-mapping>
    <field-name>resultId</field-name>
    <column-name>Attribute.resultId</column-name>
    </cmp-field-mapping>
    </entity-mapping>
    Here is the bean:
    package com.dataservices.common.ejb.entity.attribute;
    import javax.ejb.*;
    * Created Apr 13, 2005 8:05:33 AM
    * Code generated by the Sun ONE Studio EJB Builder
    * @author mebrewster
    public abstract class AttributeBean implements javax.ejb.EntityBean {
    private javax.ejb.EntityContext context;
    * @see javax.ejb.EntityBean#setEntityContext(javax.ejb.EntityContext)
    public void setEntityContext(javax.ejb.EntityContext aContext) {
    context=aContext;
    * @see javax.ejb.EntityBean#ejbActivate()
    public void ejbActivate() {
    * @see javax.ejb.EntityBean#ejbPassivate()
    public void ejbPassivate() {
    * @see javax.ejb.EntityBean#ejbRemove()
    public void ejbRemove() {
    * @see javax.ejb.EntityBean#unsetEntityContext()
    public void unsetEntityContext() {
    context=null;
    * @see javax.ejb.EntityBean#ejbLoad()
    public void ejbLoad() {
    * @see javax.ejb.EntityBean#ejbStore()
    public void ejbStore() {
    public abstract int getId();
    public abstract void setId(int id);
    public abstract int getResultId();
    public abstract void setResultId(int resultId);
    public abstract double getX();
    public abstract void setX(double x);
    public abstract double getY();
    public abstract void setY(double y);
    public abstract double getZ();
    public abstract void setZ(double z);
    public abstract java.lang.String getComments();
    public abstract void setComments(java.lang.String comments);
    public com.dataservices.common.ejb.entity.attribute.AttributeKey ejbCreate(com.dataservices.common.cbo.attribute attribute) throws javax.ejb.CreateException {
    setId(attribute.getId());
    setResultId(attribute.getResultId());
    setX(attribute.getX());
    setY(attribute.getY());
    setZ(attribute.getZ());
    setComments(attribute.getComments());
    return null;
    public void ejbPostCreate(com.dataservices.common.cbo.Attribute attribute) throws javax.ejb.CreateException {
    x, y, z are all floats in the database and in the Attribute object. If I change setX(attribute.getX()); to setX(Float.NaN); (Did this to make sure it wasn't in the code outside the beans)I get the invalid column name in list error message in the servers log file.(It doesn't matter if I change x or y or z, they all do it.)
    Thanks for your help!

  • Nothing prints for Float.NaN

    My understanding is that Float.NaN is true when 0.0f/0.0f. However, I do not get confirmation of this with a print statement.
    What am I missing here?
    public class FloatTest {
         public static void main(String[] args) {
              float floatExample;
              floatExample = -1.0f/0.0f;
              if (floatExample == Float.NEGATIVE_INFINITY)
                   System.out.println("NEGATIVE_INFINITY");
              floatExample = 1.0f/0.0f;
              if (floatExample == Float.POSITIVE_INFINITY)
                   System.out.println("POSITIVE_INFINITY");
              floatExample = 0.0f/0.0f;
              if (floatExample == Float.NaN)
                   System.out.println("NaN");
    }Thanks in advance,
    Lance

    By the definition, (f1 == f2) will be false if either or both are Float.NaN. This means that if floatExample is Float.NaN, then (floatExample == Float.NaN) will be false. If you want to see if floatExample is Float.NaN, then use the Float.isNaN(float) method.

  • System.out.println(Math.min(Float.NaN, Float.POSITIVE_INFINITY));

    System.out.println(Math.min(Float.NaN, Float.POSITIVE_INFINITY));
    This is printing Nan...
    How is it possible
    Y is it not banging with an Illegal argument Exception
    Any Idea..
    Kindly Help

    When in doubt, read the docs and/or check the source:
         * Returns the smaller of two <code>float</code> values.  That is,
         * the result is the value closer to negative infinity. If the
         * arguments have the same value, the result is that same
         * value. If either value is NaN, then the result is NaN.  Unlike
         * the numerical comparison operators, this method considers
         * negative zero to be strictly smaller than positive zero.  If
         * one argument is positive zero and the other is negative zero,
         * the result is negative zero.
         * @param   a   an argument.
         * @param   b   another argument.
         * @return  the smaller of <code>a</code> and <code>b.</code>
        public static float min(float a, float b) {
            if (a != a) return a;   // a is NaN
            if ((a == 0.0f) && (b == 0.0f)
                && (Float.floatToIntBits(b) == negativeZeroFloatBits)) {
                return b;
            return (a <= b) ? a : b;
        }

  • Setting NAN float value from Python

    I'm writing Python 2.6 code that interfaces with NI TestStand 4.2 via COM in Windows. I want to make a "NAN" value for a variable, but if I pass it float('nan'), TestStand displays it as IND. That is, my code has something like:
    locals_prop_object.NewSubProperty(var_name, win32com.client.constants.PropValType_Number, False, "", 0)
    # Set the initial value to NaN--although it appears in TestStand as 'IND'.
    locals_prop_object.SetValNumber(var_name, 0, float('nan'))
    Apparently TestStand distinguishes between floating point "IND" and "NAN" values. According to TestStand help:
    IND corresponds to Signaling NaN in Visual C++, while
    NAN corresponds to QuietNaN
    That implies that Python's float('nan') is effectively a Signaling NaN when passed through COM. However, from what I've read about Signaling NaN, it seems that Signaling NaN is a bit "exotic" and Quiet NaN is your "regular" NaN. So I have my doubts that Python would be passing a Signaling NaN through COM (how could I verify this?).
    So, any ideas how Python float('nan') becomes TestStand 'IND', in the Python->COM->TestStand data flow?
    Solved!
    Go to Solution.

    I asked this question on StackOverflow.
    From the responses, and further investigation, I've found the following:
    It is possible to inspect the value of a NaN using the Python struct module.
    >>> import struct
    >>> struct.pack(">d", float('nan')).encode("hex_codec")
    'fff8000000000000'
    With reference to a table in IEEE-754 References, we can see that this is technically the Indeterminate value.
    It is possible to construct a real Quiet NaN in Python using the struct module's struct.unpack:
    >>> quiet_nan = struct.unpack(">d", "\x7f\xf8\x00\x00\x00\x00\x00\x00")[0]
    >>> struct.pack(">d", quiet_nan).encode("hex_codec")
    '7ff8000000000000'
    I'm home sick today, without access to TestStand, but I reckon I should be able to pass this quiet_nan value to SetValNumber and it should appear as NAN in TestStand. I'll try it when I have the opportunity.
    Interestingly, I was not able to use the same method to explicitly construct a Signaling NaN. It got converted to a Quiet NaN. So perhaps the TestStand help should be updated to explicitly refer to IEEE-754 Indeterminate value which appears as IND in TestStand.
    >>> import struct
    >>> struct.pack(">d", float('nan')).encode("hex_codec")
    'fff8000000000000'

  • BatchUpdateException

    hello, there:
    I was running an jdbc-related app, and I used preparedStatement.addBatch in this app to insert data into database.
    it was fine but today I got an exception: java.sql.BatchUpdateException: Overflow Exception trying to bind NaN
    Anyone knows what causes this kind of Exception and how I can solve this problem?
    Thanks a lot,
    Sway

    It looks like you did some bad arithmetic, resulting in a "Not A Number" (NaN) result. For example:
    public class Nan {
       public static void main(String[] args) {
          float nan = 0f / 0f;
          System.out.println(nan);
    }When you then try to store that value in a floating point column, the database complains. So the problem is in your Java logic, and the database is trying to prevent you from corrupting the column!
    It's not specific to the BatchUpdate, it just happened to occur in one, and so the BatchUpdate had to report the error.
    Dave.

  • JFormattedTextField getValue() is returning the wrong type

    So this is a very strange I've found in my ever-growing project I've been working on. I have four text boxes set up. Essentially, one is the total, the second is part_one, the third part_two, and the last the_rest.
    They've all been declared and initialized identically, e.g.:
    JFormattedTextField total = new javax.swing.JFormattedTextField(java.text.NumberFormat.getCurrencyInstance(Locale.US));
    JFormattedTextField part_one = new javax.swing.JFormattedTextField(java.text.NumberFormat.getCurrencyInstance(Locale.US));
    JFormattedTextField part_two = new javax.swing.JFormattedTextField(java.text.NumberFormat.getCurrencyInstance(Locale.US));
    JFormattedTextField the_rest = new javax.swing.JFormattedTextField(java.text.NumberFormat.getCurrencyInstance(Locale.US));the_rest is supposed to auto update as any of the other three are changed (the_rest = total - part_one - part_two)
    However, I'm having issues updating the text boxes, as I am getting a ClassCastException when trying to calculate the_rest:
    float calculated = calculateTheRest((Float)total.getValue(), (Float)part_one.getValue(), (Float)part_two.getValue());
    the_rest.setValue(calculated);And my calculateTheRest() function:
    private float calculateTheRest(Float total, Float part_one, Float part_two) {
            if(total == null)
                total = 0.0f;
            if(part_one== null)
                part_one = 0.0f;
            if(part_two== null)
                part_two = 0.0f;
            return total - (first + second);
    }What am I doing wrong here?
    Edited by: GranoblasticMan on Sep 16, 2008 7:49 AM
    Fixed typos... was hand-retyping this, not copy-and-pasting.
    Edited by: GranoblasticMan on Sep 16, 2008 7:51 AM
    And the exact error message I'm getting is:
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Long

    For the time being, I've changed my calculateTheRest() function:
            private float calculateTheRest(Object total, Object part_one, Object part_two) {
            if(total == null)
                total = new Float(0.0f);
            if(part_one == null)
                first = new Float(0.0f);
            if(part_two == null)
                second = new Float(0.0f);
            return convertToFloat(total) - (convertToFloat(part_one) + convertToFloat(part_two));
    private float convertToFloat(Object o) {
            if(o instanceof Number)
                return ((Number)o).floatValue();
            return Float.NaN;   
    }But I'm still wondering why this would happen. Do FormattedTextFields not actually store decimal values?

  • Return type

    public float parseFloat( String s )
       float f = 0.0f;
       try
          f = Float.valueOf( s ).floatValue();
          return f ;
       catch(NumberFormatException nfe)
          f = Float.NaN ;
          return f;
       finally
          f = 10.0f;
          return f;
    }In the above code irrespective of whether exception is thrown or not we have 2 return types. finally is always executed, so does that mean that return of try and catch will not be executed?

    Hai,
    Yes that is true.
    In this method always the return value of this function will be 10.0f as mentioned in the finally block
    rgds,
    rdRose

  • Inconsistent Floating Point Math and NaNs on Windows Laptops?

    All -
    I am seeing some very strange inconsistent floating point calculations on Windows Laptops, and I am wondering if anyone has any ideas. Read on, as (to me!) it's very interesting....
    I have attached a segment of our code, along with some sample output. Looking at the code and the output, it seems like it's totally impossible.
    With supposedly non-NaN and non-infinite double values, I am seeing unrepeatable and inconsistent math - the below example only illustrates one such case where we're seeing this behavior.
    If you look at the code below, you will see that I do things like:
    double rhoYo = ...  // some math
    double rho = ...  // exact same mathStrangely enough, I might get rhoYo = 1.51231231 etc and rho = NaN.
    If I reverse those lines (vertically), then again, rhoYo comes out good and rho comes out NaN; however, this is unpredictable and inconsistent. If I project a source point, get a destination point with NaNs as a result, and project the source again, the second destination point may be just fine. Matter of fact, i can put a loop in the code such as:
          double rho = Double.NaN;
          for( int i = 0; i < 10; i++ )
            rho = my_earthRad * my_F / Math.pow(Math.tan(Math.PI/4.0 + latRad/2.0), my_n);
            if( ! Double.isNaN( rho ) )
              break;
            System.out.println("NaN'ed rho");
          }and rho will eventually become non-NaN (random # of iterations)!!
    How's that possible? Our code might be tromping on memory somewhere, but this sure seems crazy to me, especially considering that
    we're only using local variables. Anyone know of floating point errors on Windows Laptops?
    With the exact same codebase, this behavior ONLY happens on Windows Laptops, including brand new Dells, old Dells, IBM, Intel and AMD chips (I've tried several ;-). It does NOT happen on Mac or Linux, including the Linux side of a Linux/Windows dual-boot (where it does happen with the Windows side). Even more strangely, it does NOT happen with Windows desktops. I have tried several 1.5.x JVMs, webstart vs no webstart, etc, to no avail. Always and only on Windows Laptops.
    Please help.... ;-) and thanks in advance.
    Sample code:
    public class Projection
      protected Point2D.Double _project(Point2D.Double srcPt, Point2D.Double dstPt) {
        final double my_degToRad = Math.PI / 180.0;
        final double my_originLon = -95.0;
        final double my_originLonRad = my_originLon * my_degToRad;
        final double my_originLat = 25.0;
        final double my_originLatRad = my_originLat * my_degToRad;;
        final double my_stdLat1 = 25.0;
        final double my_stdLat1Rad = my_stdLat1 * my_degToRad;
        final double my_earthRad = 6371.2;
        final double my_n = Math.sin( my_stdLat1Rad );
        final double my_F = Math.cos( my_stdLat1Rad ) * Math.pow( Math.tan( Math.PI / 4.0 + my_stdLat1Rad / 2.0 ), my_n ) / my_n;
        final double my_rhoZero = my_earthRad * my_F / Math.pow( Math.tan( Math.PI / 4.0 + my_originLatRad / 2.0 ), my_n );
        if ( Double.isNaN( my_n ) || Double.isNaN( my_F ) || Double.isNaN( my_rhoZero )) {
          return new Point2D.Double(Double.NaN, Double.NaN);
        if( Double.isNaN( srcPt.x ) || Double.isNaN( srcPt.y ) )
            System.out.println("======= _project received a srcPt with NaNs. Returning NaN point.");
            Point2D.Double nanPoint = new Point2D.Double();
            nanPoint.x = nanPoint.y = Double.NaN;
            return nanPoint;
        if( Double.isInfinite( srcPt.x ) || Double.isInfinite( srcPt.y ) )
            System.out.println("======= _project received a srcPt with isInfinite. Returning NaN point.");
            Point2D.Double nanPoint = new Point2D.Double();
            nanPoint.x = nanPoint.y = Double.NaN;
            return nanPoint;
        //  Inputs are lon, lat degrees.
        final double lonRad = srcPt.x * my_degToRad;
        final double latRad = srcPt.y * my_degToRad;
        final double theta = my_n * (lonRad - my_originLonRad);
        // One Std lat -- tangential cone.
        final double rhoYo = my_earthRad * my_F / Math.pow(Math.tan(Math.PI/4.0 + latRad/2.0), my_n);
        final double rho   = my_earthRad * my_F / Math.pow(Math.tan(Math.PI/4.0 + latRad/2.0), my_n);
        // Computes kilometers in lambert space.
        dstPt.x = rho * Math.sin(theta);
        dstPt.y = my_rhoZero - (rho * Math.cos(theta));
        // WANK - Here's the problem!  These values shouldnt be NaN!
        if( Double.isNaN( dstPt.x ) || Double.isNaN( dstPt.y ) )
            System.out.println("======= A _projected dstPt has NaNs. Dumping...vvvvvvvvvvvvvvvvvvvvvvvvvvvv");
            if( Double.isNaN( dstPt.x ) )
                System.out.println("======= dstPt.x is NaN");
            if( Double.isNaN( dstPt.y ) )
                System.out.println("======= dstPt.y is NaN");
            System.out.println("======= my_stdLat1 = " + my_stdLat1 );
            System.out.println("======= my_n = " + my_n );
            System.out.println("======= my_originLonRad = " + my_originLonRad );
            System.out.println("======= my_F = " + my_F );
            System.out.println("======= my_earthRad = " + my_earthRad );
            System.out.println("======= lonRad = " + lonRad );
            System.out.println("======= latRad = " + latRad );
            System.out.println("======= theta = " + theta );
            System.out.println("======= Math.tan(Math.PI/4.0 + latRad/2.0) = " + Math.tan(Math.PI/4.0 + latRad/2.0) );
            System.out.println("======= Math.pow(Math.tan(Math.PI/4.0 + latRad/2.0), my_n) = " + Math.pow(Math.tan(Math.PI/4.0 + latRad/2.0), my_n) );
            System.out.println("======= rho = " + rho );
            System.out.println("======= rhoYo = " + rhoYo );
            System.out.println("======= Math.sin(theta) = " + Math.sin(theta) );
            System.out.println("======= dstPt.x = " + dstPt.x );
            System.out.println("======= Math.cos(theta) = " + Math.cos(theta) );
            System.out.println("======= my_rhoZero = " + my_rhoZero );
            System.out.println("======= (rhoYo * Math.cos(theta)) = " + (rho * Math.cos(theta)) );
            System.out.println("======= my_rhoZero - (rhoYo * Math.cos(theta)) = " + (my_rhoZero - (rho * Math.cos(theta)) ));
            System.out.println("======= dstPt.y = " + dstPt.y );
            System.out.println("======= A _projected dstPt had NaNs. Done dumping. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
        return dstPt;
    }And here's the sample output:
    ======= A _projected dstPt has NaNs. Dumping...vvvvvvvvvvvvvvvvvvvvvvvvvvvv
    ======= dstPt.x is NaN
    ======= dstPt.y is NaN
    ======= my_stdLat1 = 25.0
    ======= my_n = 0.42261826174069944
    ======= my_originLonRad = -1.6580627893946132
    ======= my_F = 2.5946660025799146
    ======= my_earthRad = 6371.2
    ======= lonRad = -2.7564670759053924
    ======= latRad = 0.3730758324037379
    ======= theta = -0.4642057102537187
    ======= Math.tan(Math.PI/4.0 + latRad/2.0) = 1.4652768116539785
    ======= Math.pow(Math.tan(Math.PI/4.0 + latRad/2.0), my_n) = 1.175224090766834
    ======= rho = NaN
    ======= rhoYo = 14066.369269924155
    ======= Math.sin(theta) = -0.44771270676160557
    ======= dstPt.x = NaN
    ======= Math.cos(theta) = 0.8941774612481554
    ======= my_rhoZero = 13663.082491950498
    ======= (rhoYo * Math.cos(theta)) = NaN
    ======= my_rhoZero - (rhoYo * Math.cos(theta)) = NaN
    ======= dstPt.y = NaN
    ======= A _projected dstPt had NaNs. Done dumping. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    HI JSchell (and others?) -
    I have created a simple example attached below, that when run repeatedly, does indeed generate spurious NaNs. I have made it as simple as possible. In the code, I use my own lon/lat binary data file, though I am sure any will do. Let me know if anyone wants that file.
    So the deal is that (with my data at least) this program should never generate NaN results. And if one runs it 25432 (eg: random #) times, it wont, but then the 25433th time, it will create NaNs, etc. ie: inconsistent NaN math results.
    As I said before, I have run this on old and new Dell laptops under Windows XP, using java 1.5_02, 1.5_04 and 1.5_08. The latest run was on a brand new Dell with a Intel Core Duo T2600 processor, running XP. If this is a result of the Pentium bug, one would think that would be fixed by now. I have NOT yet tested on AMD, though I will do that this afternoon.
    Remember, this ONLY happens with Windows Laptops.
    Any ideas anyone? Thanks in advance ;-)
    Here's the code that produces spurious NaNs:
    import java.awt.geom.Point2D;
    import java.io.DataInputStream;
    import java.io.EOFException;
    import java.io.File;
    import java.io.FileInputStream;
    public class FloatingPointTest2 implements Runnable
      private static final int NUM_ITERATIONS = 100000;
      private double _degToRad = Math.PI / 180.0;
      private double _originLon = -95.0;
      private double _originLat = 25.0;
      private double _originLonRad = _originLon * _degToRad;
      private double _originLatRad = _originLat * _degToRad;;
      private double _stdLat1 = 25.0;
      private double _stdLat1Rad = _stdLat1 * _degToRad;
      private double _earthRad = 6371.2;
      private double _n = _n = Math.sin( _stdLat1Rad );
      private double _F = Math.cos( _stdLat1Rad ) * Math.pow( Math.tan( Math.PI / 4.0 + _stdLat1Rad / 2.0 ), _n ) / _n;
      private double _rhoZero = _earthRad * _F / Math.pow( Math.tan( Math.PI / 4.0 + _originLatRad / 2.0 ), _n );
      private Point2D.Double _project( Point2D.Double srcPt, Point2D.Double dstPt )
        if( Double.isNaN( srcPt.x ) || Double.isNaN( srcPt.y ) )
          System.out.println( "FloatingPointTest2: received a NaN srcPt.  Skipping." );
          return new Point2D.Double( Double.NaN, Double.NaN );
        //  Inputs are lon, lat degrees.
        final double lonRad = srcPt.x * _degToRad;
        final double latRad = srcPt.y * _degToRad;
        final double theta = _n * ( lonRad - _originLonRad );
        double rho = _earthRad * _F / Math.pow( Math.tan( Math.PI / 4.0 + latRad / 2.0 ), _n );
        dstPt.x = rho * Math.sin( theta );
        dstPt.y = _rhoZero - ( rho * Math.cos( theta ) );
        return dstPt;
      public void doTest()
        DataInputStream instream = null;
        int thisRunNaNCount = 0;
        Point2D.Double tempPt = new Point2D.Double();
        Point2D.Double dstPt = new Point2D.Double();
        try
          instream = new DataInputStream( new FileInputStream( System.getProperty(
            "user.home" ) + File.separatorChar + "lonLatBinaryData.bin" ) );
          try
            while( true )
              double lon = instream.readDouble();
              double lat = instream.readDouble();
              if( Double.isNaN( lon ) || Double.isNaN( lat ) )
                continue;
              tempPt.x = lon;
              tempPt.y = lat;
              dstPt = _project( tempPt, dstPt );
              if( Double.isNaN( dstPt.x ) || Double.isNaN( dstPt.y ) )
                thisRunNaNCount++;
          catch( EOFException e )
    //        System.out.println( "End of file" );
          if( thisRunNaNCount > 0 )
            System.out.println( "thisRunNaNCount = " + thisRunNaNCount );
          instream.close();
        catch( Exception e )
          e.printStackTrace();
          System.exit( 1 );
      public void run()
        doTest();
      public static void main( String args[] )
        System.out.println( "Executing FloatingPointTest2." );
        for( int i = 0; i < NUM_ITERATIONS; i++ )
          FloatingPointTest2 test = new FloatingPointTest2();
          test.doTest();
    }

  • Converting byte[] to float the value become NaN even there is value existing.

    I tried from the online Sample but,  
                        Array.Reverse(data, index * 4, 4);
                        result = BitConverter.ToSingle(data, index * 4);
    When the  condition  index*4>data.length it will through exception.
    Thanks,

    Hi sasikumar.93,
    In C# the NAN is related to this:
    https://msdn.microsoft.com/en-us/library/system.double.nan(v=vs.110).aspx and also
    https://msdn.microsoft.com/en-us/library/system.single.nan.aspx
    Maybe the convert here becomes NaN field which raised the exception.
    Best regards,
    Barry
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Sscanf and NaN floating point

    I do not understand what is wrong.
    If I convert a double variable with value NaN with sprintf, it correctly converts to string "NaN".
    When I run the reverse, string to double by sscanf it fails and the number is not converted.
    I do not understand where wrong. printf and scanf should handle NaN. Where is the error?
    Help me understand.
    Test code:
    char DoubleStr[50];
    double Valdouble;
    i=0;
    DoubleStr[0]=0;
    Valdouble=NotANumber();                                           //After This Valdouble==NaN, DoubleStr=="",i==0 (OK)
    i=sprintf(DoubleStr,"%lf", Valdouble);                         //After This Valdouble==NaN, DoubleStr=="NaN", i==3 (OK)
    Valdouble=0.0;                                                                //After This Valdouble==0.0, DoubleStr=="NaN", i==3 (OK)
    i=sscanf(DoubleStr,"%lf",&Valdouble);                      //After This Valdouble==0.0, DoubleStr=="NaN", i==0 (Why "NaN" not be conveted and stored in Valdouble?)
    Thank You.

    I thank you very much for the quick response.
    After this I tried a solution "manually", and it seems to work well.
    Test code:
    char DoubleStr[50];
    double Valdouble;
    i=0;
    DoubleStr[0]=0;
    Valdouble=NotANumber();                           ​                //After This Valdouble==NaN, DoubleStr=="",i==0 (OK)
    i=sprintf(DoubleStr,"%lf", Valdouble);                         //After This Valdouble==NaN, DoubleStr=="NaN", i==3 (OK)
    Valdouble=0.0;                                    ​                            //After This Valdouble==0.0, DoubleStr=="NaN", i==3 (OK)
    i=sscanf(DoubleStr,"%lf",&Valdouble);             ​         //After This Valdouble==0.0, DoubleStr=="NaN", i==0 (Why "NaN" not be conveted and stored in Valdouble?)
    i=0;
    if(stricmp(DoubleStr,"NaN")==0)
    { Valdouble=NotANumber(); i=1; }
    else if(stricmp(DoubleStr,"+Inf")==0)
    { Valdouble=PositiveInfinity(); i=1; }
    else if(stricmp(DoubleStr,"-Inf")==0)
    { Valdouble=NegativeInfinity(); i=1; }
    else
    { i=sscanf(DoubleStr,"%lf",&Valdouble); }
    But there is some other way more elegant and faster to accomplish this?
    There anything in winapi to solve this?
    I should make parsing of large quantities of data and already the standard "sscan" is quite slow.
    Thank you very much.

  • Float overlow Exception!

    Hi all,
    To quote JLS in verbatim ..."Java floating-point
    operators produce no exceptions (�11). An operation
    that overflows produces a signed infinity, an
    operation that underflows produces a signed zero, and
    an operation that has no mathematically definite
    result produces NaN."
    But I am facing a problem here. The highest value
    that can be held by a Double variable is
    1.79769313486231570e+308. Any operation resulting in
    an overflow of this variable should produce 'infinity'
    accodring to the JLS but I am getting a
    "EXCEPTION_FLT_OVERFLOW". Does this have something to
    do with the OS or the processor?
    Here's a simple test program:
    public class FloatingPointInexactRulesTest {
    public static void main(String[] args) {
    // An example of overflow:
    double d = 1.79769313486231570e+308;
    System.out.print("overflow produces infinity: ");
    System.out.println(d + "*1.1==" + d*1.1);
    The program's output should have been:
    overflow produces infinity: 1.0e+308*1.1==Infinity
    but I get a EXCEPTION_FLT_OVERFLOW! Since the JVM cant
    violate the semantics of the JLS I think the problem
    lies somewhere else(either the OS or the processor). I
    am using WIndows2000 as the OS and Intel PIV as the
    processor.
    Please help me...
    --------------EXCEPTION!---------------------
    Unexpected Signal : EXCEPTION_FLT_OVERFLOW
    (0xc0000091) occurred at PC=0xEFA6C3
    Function=[Unknown.]
    Library=(N/A)
    NOTE: We are unable to locate the function name symbol
    for the error
    just occurred. Please refer to release
    documentation for possible
    reason and solutions.
    Current Java thread:
    Dynamic libraries:
    0x00400000 - 0x00407000
    C:\j2sdk1.4.2_04\bin\java.exe
    0x77F80000 - 0x77FFD000
    C:\WINNT\system32\ntdll.dll
    0x7C2D0000 - 0x7C332000
    C:\WINNT\system32\ADVAPI32.dll
    0x7C570000 - 0x7C628000
    C:\WINNT\system32\KERNEL32.DLL
    0x77D30000 - 0x77D9E000
    C:\WINNT\system32\RPCRT4.DLL
    0x78000000 - 0x78045000
    C:\WINNT\system32\MSVCRT.dll
    0x00250000 - 0x002C3000
    C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\uga1.tmp
    0x71710000 - 0x71794000
    C:\WINNT\system32\COMCTL32.DLL
    0x77F40000 - 0x77F7E000
    C:\WINNT\system32\GDI32.dll
    0x77E10000 - 0x77E75000
    C:\WINNT\system32\USER32.DLL
    0x76620000 - 0x76630000
    C:\WINNT\system32\MPR.DLL
    0x77A50000 - 0x77B3C000
    C:\WINNT\system32\OLE32.DLL
    0x779B0000 - 0x77A4B000
    C:\WINNT\system32\OLEAUT32.DLL
    0x75050000 - 0x75058000
    C:\WINNT\system32\WSOCK32.DLL
    0x75030000 - 0x75044000
    C:\WINNT\system32\WS2_32.DLL
    0x75020000 - 0x75028000
    C:\WINNT\system32\WS2HELP.DLL
    0x08000000 - 0x08138000
    C:\j2sdk1.4.2_04\jre\bin\client\jvm.dll
    0x77570000 - 0x775A0000
    C:\WINNT\system32\WINMM.dll
    0x10000000 - 0x10007000
    C:\j2sdk1.4.2_04\jre\bin\hpi.dll
    0x00CE0000 - 0x00CEE000
    C:\j2sdk1.4.2_04\jre\bin\verify.dll
    0x00CF0000 - 0x00D09000
    C:\j2sdk1.4.2_04\jre\bin\java.dll
    0x00D10000 - 0x00D1D000
    C:\j2sdk1.4.2_04\jre\bin\zip.dll
    0x77920000 - 0x77943000
    C:\WINNT\system32\imagehlp.dll
    0x72A00000 - 0x72A2D000
    C:\WINNT\system32\DBGHELP.dll
    0x690A0000 - 0x690AB000
    C:\WINNT\system32\PSAPI.DLL
    Heap at VM Abort:
    Heap
    def new generation total 576K, used 197K
    [0x10010000, 0x100b0000, 0x104f0000)
    eden
    Another exception has been detected while we were
    handling last error.
    Dumping information about last error:
    ERROR REPORT FILE = (N/A)
    PC = 0x00efa6c3
    SIGNAL = -1073741679
    FUNCTION NAME = (N/A)
    OFFSET = 0xFFFFFFFF
    LIBRARY NAME = (N/A)
    Please check ERROR REPORT FILE for further
    information, if there is any.
    Good bye.
    --------------EXCEPTION!---------------------
    Thanks a lot.

    Yeah switching to Linux is a good idea. The firsttime I tried that,
    GRUB crashed and I screwed everything else tryingto copy the
    bootloader. Before this I had problems accessingthe file system on
    Windows via LAN, Samba server is not really theeasiest to use.
    Before that I had display problems with wierdmessages like sync out
    of range, Init respawning too fast so disabling.......I guess this is just
    the tip of an iceberg when it comes to problemswith Linux. It is
    sometimes really frustrating.Really? The only problems I recognise are the
    automatic chip set
    detection for the graphics card. I always let it boot
    in 'mode 3', figure
    out the exact chip set present in the computer and
    only then switch
    to 'mode 5' ...Yeah I had all these problems with RH Linux within a span of 2 months.
    I solved most of them though(Google is my best friend ;). The problem with the display was coz of horizontal and vertical sync values.
    btw, Samba has a nice webbrowser interface; I simply
    follow the docs
    step by step (I know next to nothing about Samba) and
    I'm in business
    after typing in all the required stuff ...I had problems with Samba bcoz of the firewall settings and the firewall interface was not comin on properly on the display.
    And now there are viruses for Linux too!Never do anything online when logged in as root and
    keep your FS
    permissions sensible.Yeah. I dont log in to root untill it is really really needed.
    An offtopic question (hope no one minds) Is there any book for Linux which is on the same lines of "The Design of the Unix Operating System" by Maurice.J.Bach?. If yes, then pls pls lemme know. I am a big Fan of "The Design of the Unix Operating System".
    kind regards,
    JosThanks and regards.

  • NaN values in array

    Hello
    I had a code done by my colleague who is not working with us anymore. In an array 8 columns and programmatically generated no. of rows all values initialize as NaN values. I have never come across NaN values before.
    From research I gather it is not a number but it really isn't making much sense to me. Why the cells in array are written as NaN? What is the significance of NaN? Can I leave the cells empty and not showing NaN in it?
    Kind Regards
    Austin
    Solved!
    Go to Solution.

    Hi Austin,
    for the constant you can use the standard numeric constant (set to any floating point format) and type "NaN" into it.
    As NaN is a number you can type it into numeric inputs... (The same applies to +Inf and -Inf, they are standard numbers too!)
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Convert float to 4 bytes array

    How can I convert float type to 4 byte array -
    not with strings but to exact binary representation.

    See the javadoc of Float.floatToIntBits. Converting an int to an array of 4 bytes is easy, so I will left it as an exercise.
    floatToIntBits
    public static int floatToIntBits(float value)Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "single format" bit layout.
    Bit 31 (the bit that is selected by the mask 0x80000000) represents the sign of the floating-point number. Bits 30-23 (the bits that are selected by the mask 0x7f800000) represent the exponent. Bits 22-0 (the bits that are selected by the mask 0x007fffff) represent the significand (sometimes called the mantissa) of the floating-point number.
    If the argument is positive infinity, the result is 0x7f800000.
    If the argument is negative infinity, the result is 0xff800000.
    If the argument is NaN, the result is 0x7fc00000.
    In all cases, the result is an integer that, when given to the intBitsToFloat(int) method, will produce a floating-point value the same as the argument to floatToIntBits (except all NaN values are collapsed to a single "canonical" NaN value).
    Parameters:
    value - a floating-point number.
    Returns:
    the bits that represent the floating-point number.

  • Annoying String to Float in AS3

    Hey again,
    I am working on *AS3* here.
    Problem: I have a value stored in a String. I'd like to check
    whether
    that String is a float. I am aware of the method
    parseFloat(string)
    described here:
    http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/
    actionscript_dictionary620.html
    However, this method has annoying limitations:
    parseFloat("2.5") will be 2.5
    parseFloat(" 2.5") will be 2.5
    parseFloat("2.5garbage") will be 2.5
    parseFloat("2.5garbage3.2") will be 2.5
    it will only be NaN if the value of the string starts with a
    non-
    numerical character
    parseFloat("garbage2.5") will be NaN
    So doing something like that, will not work for me:
    public function isFloat : Boolean(str : String) {
    if (isNaN(parseFloat(str))) {
    return false;
    return true;
    I want to check if the string is a *real* float that is:
    isFloat("2.5") will be true
    isFloat("x2.5") will be false
    isFloat("2.5x3.2") will be false
    isFloat("2.5x") will be false
    Basically, no spaces or non-numerical characters should be
    allowed
    (expect the one dot '.' if required).
    I'm thinking of implementing my own isFloat method, checking
    character by
    character to see if the value is really a float or not.
    Something like
    that (quick draft, haven't tested it or compiled it):
    public function isFloat : Boolean (str : String) {
    var dotUsed : Boolean = false;
    for (var i : int = 0; i < str.length; ++i) {
    if (str.charAt(i) == '.') {
    if (!dotUsed) {
    dotUsed = true;
    } else {
    return false;
    } else if (isNaN(parseInt(str.charAt(i)))) {
    return false;
    However, I'm not happy with the runtime efficiency here. I'm
    sure there's
    some more efficient way to detect that a string is a float;
    or another
    simple method I haven't look at.
    Any thoughts?
    Thanks

    You can avoid the looping test by using a regular expression.
    Basically the whole check could be done with a regular expression.
    I'd love to provide the code, but regular expressions are new to me
    as well. I had a play around with them and got close, but it didn't
    pass all the tests, so I wasn't doing something right. Someone else
    will post an example I'm sure.

Maybe you are looking for