Designing for floating point error

Hello,
I am stuck with floating point errors and I'm not sure what to do. Specifically, to determine if a point is inside of a triangle, or if it is on the exact edge of the triangle. I use three cross products with the edge as one vector and the other vector is from the edge start to the query point.
The theory says that if the cross product is 0 then the point is directly on the line. If the cross product is <0, then the point is inside the triangle. If >0, then the point is outside the triangle.
To account for the floating point error I was running into, I changed it from =0 to abs(cross_product)<1e-6.
The trouble is, I run into cases where the algorithm is wrong and fails because there is a point which is classified as being on the edge of the triangle which isn't.
I'm not really sure how to handle this.
Thanks,
Eric

So, I changed epsilon from 1e-6 to 1e-10 and it seems to work better (I am using doubles btw). However, that doesn't really solve the problem, it just buries it deeper. I'm interested in how actual commercial applications (such as video games or robots) deal with this issue. Obviously you don't see them giving you an error every time a floating point error messes something up. I think the issue here is that I am using data gathered from physical sensors, meaning the inputs can be arbitrarily close to each other. I am worried though that if I round the inputs, that I will get different data points with the exact same x and y value, and I'm not sure how the geometry algorithms will handle that. Also, I am creating a global navigation mesh of triangles with this data. Floating point errors that are not accounted for correctly lead to triangles inside one another (as opposed to adjacent to each other), which damages the integrity of the entire mesh, as its hard to get your program to fix its own mistake.
FYI:
I am running java 1.6.0_20 in Eclipse Helios with Ubuntu 10.04x64
Here is some code that didn't work using 1e-6 for delta. The test point new Point(-294.18294451166435,-25.496614108304477), is outside the triangle, but because of the delta choice it is seen as on the edge:
class Point
     double x,y;
class Edge
     Point start, end;
class Triangle
     Edge[] edges;
     public Point[] getOrderedPoints() throws Exception{
          Point[] points = new Point[3];
          points[0]=edges[0].getStart();
          points[1]=edges[0].getEnd();
          if (edges[1].getStart().equals(points[0]) || edges[1].getStart().equals(points[1]))
               points[2]=edges[1].getEnd();
          else if (edges[1].getEnd().equals(points[0]) || edges[1].getEnd().equals(points[1]))
               points[2]=edges[1].getStart();
          else
               throw new Exception("MalformedTriangleException\n"+this.print());
          orderNodes(points);
          return points;
        /** Orders node1 node2 and node3 in clockwise order, more specifically
      * node1 is swapped with node2 if doing so will order the nodes clockwise
      * with respect to the other nodes.
      * Does not modify node1, node2, or node3; Modifies only the nodes reference
      * Note: "order" of nodes 1, 2, and 3 is clockwise when the path from point
      * 1 to 2 to 3 back to 1 travels clockwise on the circumcircle of points 1,
      * 2, and 3.
     private void orderNodes(Point[] points){
          //the K component (z axis) of the cross product a x b
          double xProductK = crossProduct(points[0],points[0], points[1], points[2]);
          /*        (3)
           *          +
           *        ^
           *      B
           * (1)+             + (2)
           *       ------A-->
           * Graphical representation of vector A and B. 1, 2, and 3 are not in
           * clockwise order, and the x product of A and B is positive.
          if(xProductK > 0)
               //the cross product is positive so B is oriented as such with
               //respect to A and 1, 2, 3 are not clockwise in order.
               //swapping any 2 points in a triangle changes its "clockwise order"
               Point temp = points[0];
               points[0] = points[1];
               points[1] = temp;
class TriangleTest
     private double delta = 1e-6;
     public static void main(String[] args)  {
                Point a = new Point(-294.183483785282, -25.498196740397056);
          Point b = new Point(-294.18345625812026, -25.49859505161433);
          Point c = new Point(-303.88217906116796, -63.04183512930035);
          Edge aa = new Edge (a, b);
          Edge bb = new Edge (c, a);
          Edge cc = new Edge (b, c);
          Triangle aaa = new Triangle(aa, bb, cc);
          Point point = new Point(-294.18294451166435,-25.496614108304477);
          System.out.println(aaa.enclosesPointDetailed(point));
      * Check if a point is inside this triangle
      * @param point The test point
      * @return     1 if the point is inside the triangle, 0 if the point is on a triangle, -1 if the point is not is the triangle
      * @throws MalformedTriangleException
     public int enclosesPointDetailed(LocalPose point, boolean verbose) throws Exception
          Point[] points = getOrderedPoints();          
          int cp1 = crossProduct(points[0], points[0], points[1], point);
          int cp2 = crossProduct(points[1], points[1], points[2], point);
          int cp3 = crossProduct(points[2], points[2], points[0], point);
          if (cp1 < 0 && cp2 <0  && cp3 <0)
               return 1;
          else if (cp1 <=0 && cp2 <=0  && cp3 <=0)
               return 0;
          else
               return -1;
         public static int crossProduct(Point start1, Point start2, Point end1, POint end2){
          double crossProduct = (end1.getX()-start1.getX())*(end2.getY()-start2.getY())-(end1.getY()-start1.getY())*(end2.getX()-start2.getX());
          if (crossProduct>floatingPointDelta){
               return 1;
          else if (Math.abs(crossProduct)<floatingPointDelta){
               return 0;
          else{
               return -1;
}

Similar Messages

  • Invalid Floating Point Error

    I have one Captivate 3 project published as a Stand Alone
    project with Flash 8 selected. There are 36 slides, no audio, no
    eLearning, SWF size and quality are high.
    One person who runs this gets an "Invalid Floating Point"
    error when he tries to run it the first time. He is running Windows
    XP SP2, Firefox 3.0.4. and Flash Player 10.0.12.36. Other Captivate
    projects I've created run fine for him. This one sometimes runs
    after the first Error message.
    Any thoughts on the cause and fix?
    Thanks,
    Janet

    iMediaTouch probably doesn't support Floating Point formats - it certainly doesn't mention them in the advertising. Try saving your files as 24-bit PCMs, and they should import fine.

  • Separator for floating point numbers

    Hello,
    I work with oracle 9 and have a problem with the entry of floating point numbers.
    The separator for floating point numbers in my data is a point (5.60).
    The pre-setting of oracle is a comma (5,60).
    By inserting I get the error message:
    01722. 00000 - "invalid number"
    How can i change this setting
    Thanks for Help
    F.

    Hi,
    I'm not sure if I understood your problem, however the NLS_NUMERIC_CHARACTERS variable specifies the characters to use as the group separator and decimal character.
    SQL> create table t1 (val number);
    Table created.
    SQL> select * from nls_session_parameters;
    PARAMETER                      VALUE
    NLS_LANGUAGE                   AMERICAN
    NLS_TERRITORY                  BRAZIL
    NLS_CURRENCY                   R$
    NLS_ISO_CURRENCY               BRAZIL
    NLS_NUMERIC_CHARACTERS ,.
    NLS_CALENDAR                   GREGORIAN
    NLS_DATE_FORMAT                DD/MM/YYYY
    NLS_DATE_LANGUAGE              AMERICAN
    NLS_SORT                       BINARY
    NLS_TIME_FORMAT                HH24:MI:SSXFF
    NLS_TIMESTAMP_FORMAT           DD/MM/RR HH24:MI:SSXFF
    NLS_TIME_TZ_FORMAT             HH24:MI:SSXFF TZR
    NLS_TIMESTAMP_TZ_FORMAT        DD/MM/RR HH24:MI:SSXFF TZR
    NLS_DUAL_CURRENCY              Cr$
    NLS_COMP                       BINARY
    NLS_LENGTH_SEMANTICS           BYTE
    NLS_NCHAR_CONV_EXCP            FALSE
    17 rows selected.
    SQL> insert into t1 values (1.50);
    1 row created.
    SQL> select * from t1;
           VAL
           1,5
    SQL> alter session set nls_numeric_characters='.,';
    Session altered.
    SQL> select * from t1;
           VAL
           1.5Cheers
    Legatti

  • F suffix for floating point.

    Okay, I'm a proficient c++ programmer and have been learning Java for only a few weeks now.
    I have a question about the f suffix for floating point varibles such as float f = 3.14f;
    The f suffix casts this as float right? which is the same as float f = (float) 3.14; Correct?
    Why do we have to add the f suffix in the first place? Doesn't the compiler know that we want a float and not a double? (single-precision 32-bit instead of double precision 64 bit) I really do not understand the concept here or why they need the f suffix.
    Can someone explain?

    ThePHPGuy wrote:
    The f suffix denotes that the literal is of a floating-point type.Yes. The d suffix does the same.
    Java has two different types of floating-point numbers.Right.
    The type double is the default type.Right.
    The float type can have a double and a float literal. Is this true or false?No. At least not in any way I understand it.
    I think you're confusing two things:
    "floating point number" is any number in the IEEE floating point format.
    "float" is a datatype holding a 32bit floating point number.
    "double" is a datatype holding a 64bit floating point number.
    floating point number literals can be either double literals (without suffix or if the "d" suffix is used) or float literals (when the "f" suffix is used).

  • Floating Point Error

    Hi all!
    Does anybody understands the following Error Message or does anybody had it allready?
    I <u>tried</u> to write a little 3D-Engine just for fun, but the kvm doesn�t wantme to.
    Please help.
    ERROR: floating-point constants should not appear
    Error preverifying class J2mewtk.apps.DDD_Engine.src.DDD_Engine.Matrix_Operation
    com.sun.kvem.ktools.ExecutionException: Preverifier returned 1
    Build failed
    Thx in prev..

    Ok, after years it even came to me that the KVM doesn�t support floatingpoint numbers. :-)
    I found the MathFP package to be usefull for me, but can someone tell me where i have to put the package, so that i can import it? I am trying since hours ... ;-)

  • Floating-point Error (Win XP Pro, Win XP Home, Win Server 2003)

    I have installed Safari on three machines. All three are have the same issue. When I load Safari, it comes up fine. If I wait for the initial page to load completely, I will get the error below. If I hit the X (stop) before the page loads completely, I get no error. I can type a new URL (www.google.com for example) and go to the new page. But, the same thing will happen if I wait for the entire page to load. This is happening on Windows XP Home, Windows XP Professional, and Windows Server 2003 Standard. All three machines have a similiar software configuration.
    All have the following installed:
    - Skype
    - Visual Studio 2005
    - SQL Server 2005 Client Tools
    - SonicWall VPN Client
    - uTorrent
    The error is:
    The exception Floating-point invalid operation.
    (0xc0000090) occurred in the application at location 0x6dc29f5c.
    Anyone have a work-around? Is this a known issue?

    ttt

  • [solved] my C code gives floating point errors.

    I've tried to create a simple function to determine if a number is prime or not.. whenever I compile and try to run I get a floating point exception and can't quite figure out why, I'm very new to C and compiling manually using gcc so any help is appreciated.
    here's my code: http://pastebin.com/m2f19dbac
    Last edited by zandaa (2008-10-01 06:36:35)

    I'm quite useless at programming:
    for (i=0; i <= x; i++) {
    if (x%i == 0 && i != 1) {
    result = 0;
    //break;
    if (i == x) {
    result = 1;
    //printf("%d\n", x);
    break;
    This loop always ends with result=1 because the last loop has i=x and therefore it changes the result value to 1.
    There are also many checks you could avoid with a "smart" for cycle:
    for (i=2; i <= x; i++) {
    if (x%i == 0) {
    return 0;
    return 1
    I was able to remove the "i != 1" part by having the for loop starting from 2.
    I removed all the if (i == x) clause because that only happens at the end of the for cycle.
    Also you could be smart and eliminate some values from the loop: for example you could avoid checking all the numbers higher than n/2 or than sqrt(n), but that's more related to the mathematics behind than to the programming
    Hope this helps
    edit: beaten
    Last edited by carlocci (2008-09-25 21:36:04)

  • Regular Expression for floating point numeric field

    Hi,
    the requirements for the field are as follows:
    - floating point numeric field 7 digits in length
    - the field must contain a decimal (dot) and either one, two or three digits to the right of the decimal
    - (leading zeroes are required if needed to fill up the 7 characters)
    My example shown below does not check for the length of 7 characters:
    public static void main(String[] args) {
        String str = "04100.0";
        System.out.println(str);
        Pattern f_1To7 = Pattern.compile("^([0-9]*\\.[0-9]{1,3})$");
        Matcher matcher = f_1To7.matcher(str);
        if (matcher.find()) {
            // yes, we've found something
            System.out.println("We matched the pattern!");
        } else {
            System.out.println("Better luck next time!");
    }When changing the pattern to
    ^([0-9]*\\.[0-9]{1,3}){7}$the whole expression will be repeated 7 times - but I would like to have to whole String to be 7 characters long.
    Here are some examples for the field:
    050.500 or 04100.0Thanks a lot and best regards,
    - Stephan

    Jackler wrote:
    Perhaps I did not express clearly enough. My problem is not a java issue - what I need is a regular expression (pattern) suiting my requirements:
    -floating point numeric field 7 digits in length
    -contains a decimal and either one, two or three digits to the right of the decimal
    ...Assuming that you are going to use Java*, you could use a lookahead at the start of your regex:
    "^(?=\\d{4,6}\\.\\d{1,3}$).{8}$"Meaning:
    ^             # match the start of the string
    (?=           #
      \d{4,6}     #   ensure that there are between 4 and 6 digits...
      \.          #   followed by a DOT...
      \d{1,3}     #   followed by 1 to 3 digits
    .{8}$         # match exactly 8 characters directly followed by the end of the string* or some other language that has look-ahead support (most PCRE implementations have them)

  • Byte Order for Floating Point Types

    I need to send an array of floating point values from an x86 C++ application to a Java application. I am using a socket to transfer the data. What, if anything, do I have to do about preserving the correct byte order?

    Probably nothing.
    If you do end up having a problem, look at the java.nio package. Specfically, java.nio.ByteOrder, and java.nio.Double/FloatBuffer.
    To be completely safe, I think I'd probably send an enum in some kind of header that indicates what byte order your C++ is sending and use the *Buffer classes to automatically handle the conversion.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • What's the best way to deal with floating point errors?

    What's the best way to deal with the decimal number errors in Flex?
    Lets say I have:
    var number1:Number = 1.1;
    var number2:Number = 1;
    var result:Number = number1 - number2;
    trace(result);
    I get "0.10000000000000009".
    What's the best way to deal with this so that i get the right result?
    Using the trick: result = Math.round( result * Math.pow(10,13) ) / Math.pow(10,13); is not useful as such when using big numbers.
    For example, If number1 = 100000000001.1, and number2 = 0.2, I get "100000000000.90001" as result. The previous rounding fixes rounding errors after 13th decimal, but here the first rounding errors come after 4 digits.
    The toPrecision method in Number and NumberFormatter dont seem be of use by themselves because of the same reason.
    So I'd have to check how big the number is, and then round the number based on that.
    So far I've constructed a method that does that with logarithms like this:
    public function floatFix(number:Number):Number{
          var precision:int = 14-Math.floor(Math.log(Math.abs(number))*Math.LOG10E);
          var precisionFactor:Number = Math.pow(10, precision);
          return Math.round(Number(number*precisionFactor))/precisionFactor;
    It just seems rather odd that one would have to create and use something like that to just count 1.1-1; There's a lot of calculating in that method, and i'm guessing that having to use that in a loop could slow down a program quite a bit.
    I think there really should be a pre-built method in flex for something like this, but I can't find any.
    Anyone know any better/faster ways?

    Use the application server database pooling services to create a datasource that can be access using JNDI.
    Move the database access code to a Servlet so that a JSP submits a form to the Servlet that does the database access and packages the data into a bean which is passed to another JSP to be displayed.

  • Performance for floating point/packed decimal arithmec expressions

    Hi,
    i need to loop over a big internal table doing some intense mathemtical operations with floating numbers.
    The compiler does not allow this:
      a = 60.0 * b.
    Instead i have to write
      a = '60.0' * b.
    Now i'm afraid that the string 60.0 is converted to float in every loopstep. This conversion is just wasting of time. Even if i use
      a = 60 * b.
    there will be a lots of conversions from interger to float.
    My first question is if i'm right that '60.0' is converted over and ovber again to float and the second one is how can i avoid that?
    My first idea is to define constants with the right type and then use these constants inside the loop avoidung the conversions. Any other ideas, hints, corrections to my assumptions?

    i went to SE30 Tips&Tricks and compared
    constants:
      co_60 type float value '60.0'.
    data:
      a type float,
      b type float.
    a = 3.
    do 10000 times.
      a = b * co_60.
    enddo.
    with
    constants:
      co_60 type float value '60.0'.
    data:
      a type float,
      b type float.
    a = 3.
    do 10000 times.
      a = b * '60.0'.
    enddo.
    there is a significant difference in the runtime. I guess the compiler does not really optimize here.
    By the way: i cant understand OSS Note 1465138.... if i have S_DEVELOP i can execute code with se38, its irrelevant id se30 is open for editing or not...i made a copy of rshowtim in D system

  • Need help||||||||||floating point error

    my code is this
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.sql.*;
    import java.math.*;
    * This class implements the Portfolio tab appearing on the System Tabs.
    * The purpose of this class is to implement a JTable that will list the details of all the companies
    * listed under the selected portfolio, which the user will choose from the Choose Portfolio Tab.
    public class PortfolioTable extends JPanel
         String t,totalPl,PPL;
         double CP=0;
         double total=0,overallPL=0;
         double totalperChange=0;
    * The PortfolioTable Class Constructor. This Constructor creates a JTable, and populates the
    * JTable with the details of the companies under the selected portfolio
    public PortfolioTable()
              // Creating objects for the various panels present
              JPanel p1 = new JPanel();
              JPanel p2 = new JPanel();
              JPanel p3 = new JPanel();
              JPanel p4 = new JPanel();
              JPanel p5 = new JPanel();
              // A boolean type variable
              boolean flag = false;
              // Creating a label. This label is shown when no companies are present under any selected portfolio, or no portfolio is selected.
              JLabel label = new JLabel("THERE ARE NO COMPANIES WITHIN THE SELECTED PORTFOLIO. TO ADD A COMPANY PLEASE GOTO THE 'PORTFOLIO ACTIONS' MENU ITEM AND THEN ADD A COMPANY.");
              JLabel label1 = new JLabel("Overall Amount Invested ");
              JLabel label2 = new JLabel("Overall Profit/Loss ");
              JLabel label3 = new JLabel("Overall Percentage Change");
              JLabel label4 = new JLabel("Amount Invested");
              JLabel label5 = new JLabel(" Profit/Loss ");
              JLabel label6 = new JLabel(" Percentage Change");
              // The following string array holds the JTable Column headers.
              String[] columnNames = {"Company Name","Previous Close (p)","Open (p)","Bid (p)","Ask (p)","Change Value","No. of Shares","Total (Pd)","Current (Pd)","Commission","Profit/Loss (Pd)","% Change"};
              // Creating an object of the JTable
              JTable table;
              // The following variables are defined to communicate with the database.
              Connection     Conn;          // The Connection object variable
              Statement     Stmt;          // The Statement object variable.
              ResultSet     rs;               // The Resultset object variable.
              // Below I'm attempting to retrieve the JDBC-ODBC Class definition
              try
                   Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
              catch(ClassNotFoundException e)
                   System.out.println("Unable to retrieve the JDBC-ODBC Bridge. Exiting.....");
                   System.exit(1);
              int i = 0;
              try
                   // Creating an database connection using the DSN - DataStorage
                   Conn = DriverManager.getConnection("jdbc:odbc:DataStorage","","");
                   Stmt = Conn.createStatement();
                   String queryString = "select COMPANYNAME,PREVCLOSE,OPEN,BID,ASK,TODAYSCHANGE,NOOFSHARES,TOTPRICEPAID FROM CompanyDetails where UNIQUEID = " + Variables.getSelectedPortfolio ();
                   // Executing the above SQL query. The values returned by the executeQuery statement is placed in the Resultset rs.
                   rs = Stmt.executeQuery(queryString);
                   // A counter variable. this counter is incremented for each record present in the table.
                   // I'm following this procedure to show only the same number of JTable rows as the number of records.
                   int count = 0;
                   while (rs.next())
                        count ++;
                   // Closing all Data Objects created above
                   rs.close();
                   Stmt.close();
                   Conn.close();
                   // Now since I know the number of records, I will initialize a String array only to the size as the number of rows present in the table.
                   // As mentioned earlier the number of rows will be determined from the variable count, declared above.
                   String rowData[][] = new String[count][12];
                   // Instantiating the JTable object created above, with the declared Column headings and the row data.
                   table = new JTable(rowData, columnNames);          
                   // Creating an database connection using the DSN - DataStorage
                   Conn = DriverManager.getConnection("jdbc:odbc:DataStorage","","");
                   Stmt = Conn.createStatement();
                   queryString = "select COMPANYNAME,PREVCLOSE,OPEN,BID,ASK,TODAYSCHANGE,NOOFSHARES,TOTPRICEPAID FROM CompanyDetails where UNIQUEID = " + Variables.getSelectedPortfolio ();
                   // Executing the above SQL query. The values returned by the executeQuery statement is placed in the Resultset rs.
                   rs = Stmt.executeQuery(queryString);
                   int j = 0;
                   // Getting the current Commision Rate. This value is retrieved from the database when the application is started and is stored in the
                   // Application variable. The Variables class handles all by Application related work.
                   String commissionVal = Variables.getCommisionValue ();
                   // Retrieving all the records.
                   while(rs.next())
                        flag = true;                                   // this variable is initialized to true to indicate that some records were found.
                        String companyName = rs.getString(1);     // the company value retrieved from the DB
                        String prevCloseStr = rs.getString(2);     // the Previous Close retrieved from the DB
                        String openPriceStr = rs.getString(3);     // the Open Price retrieved from the DB
                        String bidPriceStr = rs.getString(4);     // the Bid Price retrieved from the DB
                        String askPriceStr = rs.getString(5);     // the Ask Price retrieved from the DB
                        String todaysChg = rs.getString(6);     // the Today's Change retrieved from the DB
                        String noofShares = rs.getString(7);     // the No of Shares retrieved from the DB
                        String totPrice = rs.getString(8);     // the Total Price paid for the above shares retrieved from the DB
                        // Determining the Current Price, where it is calculated by = Current Price = Bid Price * No of Shares bought
                        double currPrice = Double.valueOf(bidPriceStr).doubleValue() * Double.valueOf (noofShares).doubleValue ();
                        // Since the Bid Price is in pence, therefore the Current Price will also be in cents. I now convert then into Pounds.
                        currPrice = currPrice/100;
                        // Determining the precision upto 2 decimal places.
                        currPrice = new java.math.BigDecimal(currPrice).setScale(2,java.math.BigDecimal.ROUND_HALF_EVEN).doubleValue ();
                        // Creating a string variable for the Current Price. This string will help me to place the value into the JTable
                        String currPriceStr = new String();
                        // calculating the profit loss. the Profit/Loss is calculated by the Current Price - Total Price. If negative then loss, if positive the profit.
                        double profitloss = currPrice - Double.valueOf(totPrice).doubleValue();
                        // Determining the precision upto 2 decimal places.
                        profitloss = new java.math.BigDecimal(profitloss).setScale(2,java.math.BigDecimal.ROUND_HALF_EVEN).doubleValue ();
                        // Creating a string variable for the Profit Loss. This string will help me to place the value into the JTable
                        String profitLossStr = new String();
                        // calculating the percentage change. The percentage Change is calculated by the profitloss/Total Price. the result value is divided by 100 to get in % profit or loss.
                        double perChange = (profitloss / Double.valueOf(totPrice).doubleValue()) * 100;
                        // Determining the precision upto 2 decimal places.
                        perChange = new java.math.BigDecimal(perChange).setScale(2,java.math.BigDecimal.ROUND_HALF_EVEN).doubleValue ();
                        // Creating a string variable for the Percentage Change. This string will help me to place the value into the JTable
                        String perChangeStr = new String();
                        // The following statements are populating the JTable columns with the appropriate values.
                        table.setValueAt(companyName,i,j);     // Company Name
                        j = j + 1;
                        table.setValueAt(prevCloseStr,i,j);     // Previous Close
                        j = j + 1;
                        table.setValueAt(openPriceStr,i,j);     // Open Price
                        j = j + 1;
                        table.setValueAt(bidPriceStr,i,j);     // Bid price
                        j = j + 1;
                        table.setValueAt(askPriceStr,i,j);     // Ask Price
                        j = j + 1;
                        table.setValueAt(todaysChg,i,j);     // Today's Change
                        j = j + 1;
                        table.setValueAt(noofShares,i,j);     // No of Shares
                        j = j + 1;
                        table.setValueAt(totPrice,i,j);          // Total Price Paid
                        j = j + 1;
                        table.setValueAt(currPriceStr.valueOf (currPrice),i,j);
                        j = j + 1;
                        table.setValueAt(commissionVal,i,j);     // Commission
                        j = j + 1;
                        table.setValueAt(profitLossStr.valueOf(profitloss),i,j);     // Profit/Loss
                        j = j + 1;     
                        table.setValueAt(perChangeStr.valueOf(perChange),i,j);          // Percentage Change
                        i = i + 1;
                        j = 0;
                        //currPrice = 0;
                        //profitloss = 0;
                        //perChange = 0;
                   //JFrame frame=new ExitableJFrame();
    //Container contentPane=frame.getContentPane();
                        total=total+Double.valueOf(totPrice).doubleValue();
                        currPrice = Double.valueOf(bidPriceStr).doubleValue() * Double.valueOf (noofShares).doubleValue ();
                        CP=CP+currPrice;
                        CP=CP/100;
                        overallPL=CP-total;
                        totalperChange=overallPL/total;     
                        totalperChange = new java.math.BigDecimal(totalperChange).setScale(2,java.math.BigDecimal.ROUND_HALF_EVEN).doubleValue ();
    t=Double.toString(total);
                        label4.setText(t);
                        totalPl=Double.toString(overallPL);
                        label5.setText(totalPl);
                        PPL=Double.toString(totalperChange);
                        label6.setText(PPL);
                        p1.add(table.getTableHeader(), BorderLayout.NORTH);
                        p2.add(table);
                        p2.setLayout(new GridLayout(10,0,5,5));
                        p4.add(label1,BorderLayout.NORTH);
                        p4.add(label2,BorderLayout.SOUTH);
                        p4.add(label3,BorderLayout.NORTH);
                        p5.add(label4,BorderLayout.SOUTH);
                        p5.add(label5,BorderLayout.NORTH);
                        p5.add(label6,BorderLayout.SOUTH);
              catch(SQLException e)
                   System.out.println(e.getMessage ());
              // Here I'm placing the various panels and the JTable onto the Frame
    Box horibox1 = Box.createHorizontalBox();
    horibox1.add(p1);
    Box horibox2 = Box.createHorizontalBox();
    horibox2.add(p2);
    Box horibox3 = Box.createHorizontalBox();
    horibox3.add(p4);
    Box horibox4 = Box.createHorizontalBox();
    horibox4.add(p5);
              if (!flag)
                   p3.add(label);
    Box veribox = Box.createVerticalBox();
    veribox.add(horibox1);
    veribox.add(Box.createGlue());
    veribox.add(horibox2);
    veribox.add(horibox3);
    //veribox.add(Box.createGlue());
    veribox.add(horibox4);
              if (!flag)
                   veribox.add(p3);
                   veribox.add(Box.createGlue());               
              this.add(veribox);
    //main method for testing purposes
    public static void main(String[] args)
    // Create a JFrame
    JFrame frame = new JFrame("Portfolio Summary");
    // Create a Portfolio Table
    PortfolioTable portfolioTableObj = new PortfolioTable();
    // Add the Portfolio Table to the JFrame
    frame.getContentPane().add(portfolioTableObj, BorderLayout.WEST);
    // Set Jframe size
    frame.setSize(800, 400);
    // Set JFrame to visible
    frame.setVisible(true);
         // set the close operation so that the Application terminates when closed
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    but when i run i get messege by calling applcaton.java i get
    C:\JavaProjectnew>java Application
    Exception in thread "main" java.lang.NullPointerException
    at java.lang.FloatingDecimal.readJavaFormatString(Unknown Source)
    at java.lang.Double.valueOf(Unknown Source)
    at TradingHistory.<init>(TradingHistory.java:156)
    at SystemTabs.<init>(SystemTabs.java:18)
    at Application.<init>(Application.java:31)
    at Application.main(Application.java:87)

    sorry for trouble
    actaually db's first record has the null value.it is solved now.
    sorry again
    sheetal

  • Error on floating point?

    One can expect that 1.2 * 3.0 equals 3.60
    But the following statement has the result: 3.5999999999999996
    - System.out.println(1.2 * 3.0);
    Why?
    How can I control or estimate the floating point error?
    Thanks in advance!

    It is not a Java problem or a Java error. It is inherent to floating-point arithmetic.
    1.2 can not be exactly represented in binary floating-point arithmetic. But 1.25 (that is 5 * (2 ^ -2)) can be.
    If your problem requires exact decimal arithmetic, use BigDecimal instead. (It is very slow compared to the conventional floating-point arithmetic).
    Please consult a textbook on numerical calculus for the techniques of dealing with floating-point error - it depends on the algorithm that you use for solving your problem.

  • 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();
    }

  • Floating Point Representations on SPARC (64-bit architecture)

    Hi Reader,
    I got hold of "Numerical Computation Guide -2005" by Sun while looking for Floating Point representations on 64 bit Architectures. It gives me nice illustrations of Single and Double formats and the solution for endianness with
    two 32-bit words. But it doesn't tell me how it is for 64-bit SPARC or 64-bit x86.
    I might be wrong here, but having all integers and pointers of 64-bit length, do we still need to break the floating point numbers and store them in lower / higher order addresses ??
    or is it as simple as having a Double Format consistent in the bit-pattern across all the architectures (Intel, SPARC, IBMpowerPC, AMD) with 1 + 11 + 52 bit pattern.
    I have tried hard to get hold of a documentation that explains a 64-bit architecture representation of a Floating Point Number. Any suggestion should be very helpful.
    Thanks for reading. Hope you have something useful to write back.
    Regards,
    Regmee

    The representation of floating-point numbers is specified by IEEE standard 754. This standard contains the specifications for single-precision (32-bit), and double-precision (64-bit) floating-point numbers (There is also a quad-precision (128-bit) format as well). OpenSPARC T1 supports both single and double precision numbers, and can support quad-precision numbers through emulation (not in hardware). The fact that this is a 64-bit machine does not affect how the numbers are stored in memory.
    The only thing that affects how the numbers are stored in memory is endianness. SPARC architecture is big-endian, while x86 is little-endian. But a double-precision floating-point numer in a SPARC register looks the same as a double-precision floating-point number in an x86 register.
    formalGuy

Maybe you are looking for

  • Looking for Help to Locate my Itunes Library

    I had Itunes installed on a laptop who's mother board fried. I had purchased songs and ones I had uploaded from cd's. I'm using an old laptop we had as a spare and installed Itunes, authorized the computer and imported the library. Trouble is, the on

  • GR/IR difference with foreign currency - WBS element

    I am working in the MM area and hadling Service entry sheets, GR and Invoice, Finance is complaining and having problem at project(WBS Element) closing time. we are using Project system to control budget. Now finance is not able to close budget code

  • Viewing Bind variable values in TKPROF output

    DB Version:10gR2 After tracing a Stored proc , i can see the bind variable values in the raw trace file. But the TKPROF output of this trace file doesn't show Bind variable values. Is there a way i could see Bind variable values in TKPROF output?

  • ACE sending malformed requests?

    Hi, Our ACE has several contexts, and in one of them we are seeing a single probe fail at random times, to a single particular rserver. The logs of the ACE and the affected rserver at the same time are: ACE logs: %ACE-3-251010 Health probe failed for

  • Use of Write Key VI with an array of cluster

    Hi, I wanted to use an array of clusters to define some configuration parameters for an application. Unfortunately, "Write Key VI" doesn't support the cluster type. Has anybody modified this function ("Write Key VI") to support cluster and array of c