Why java gives wrong answer

float f=40.3f;
System.out.println(f%4);
The answer for above must be 0.3 but java gives 0.29999924
WHY????
(This answer is ok for small calculations but it may give wrong answers for large calculations)

float f=40.3f;
System.out.println(f%4);
The answer for above must be 0.3 but java gives
0.29999924
WHY????
(This answer is ok for small calculations but it may
give wrong answers for large calculations)Use BigDecimal with MathContext or roll your own Fraction class- this way any repeating decimal is represented exactly.
Message was edited by:
snic.snac

Similar Messages

  • Numbers gives wrong answer.

    On my numbers (v3.1) spreadsheet on Mac (Mavericks, iMac , OSX 10.9.1), 83177.2-78342.53 comes out 4834.66999999999.  I'm pretty sure this is the wrong answer (there should be no repeating digit at the end.  What gives?

    John,
    this is a fact of compuing that there finite precision available.  People write very sophisticated and expensive libraries for extrememly large and small numbers.  At 11 decimal places you are past the believable, and reaonable, number of digits of precision.
    the error of 4834.66999999999 vs 4834.67 is:
    |4834.66999999999 - 4834.67| / 4834.67
    this is: 2.068e-13 percent
    I would suggest using the number of decimal places that are reasonable for your data and get something done rather than focusing on this detail.  It is not a problem and, while I am not an Apple employee, based on my experince as an embedded developer, and Electrical Engineer, and based on my experience with Apple you can expect no change with regard to this.
    If you are very interested in precision and range of digital values peruse this information:
    http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic
    and this:
    http://www.nongnu.org/hpalib/
    And this:
    https://gmplib.org

  • Multisim ac analysis for simple resonant circuit gives wrong answer

    Hello,
    I tried to run a simulation of the attached simple tank circuit and the multisim results are wrong (don't match hand calculations or microcap simulation results). I tried experimenting with simulation settings with no effect. Can you help me resolve?
    -Steve
    Attachments:
    NI Question1.pdf ‏241 KB

    Hi Steve,
    Run attached circuit, I was able to similar results as Microcap.  This screen shot shows the AC setup I used just in case you are not running Multisim 13.
    Tien P.
    National Instruments
    Attachments:
    AC.ms13 ‏59 KB
    AC.PNG ‏18 KB

  • Calculator gives wrong answer

    Imac 2,7 GHz Core i5. Mavericks updated. Calculator 10.8. I enter 10+10/2 and get 15. I enter 10+10= and get 20. I then divide result by two and get correct answer-10. But. Calculator broke the result (20) into 10+10 then divided by 2. (See entry 3 in Paper Tape). Simple 20 divided by 2 computes the correct answer-10. See Screen Capture. Any thoughts.

    Check the link below.
    http://www.mathgoodies.com/lessons/vol7/order_operations.html

  • How to trigger email notification when users fail to give correct answers to reset your password in fim 2010 r2

    Hi,
    How to trigger email notification when users fail to give correct answers to reset your password in fim 2010 r2
    Senario:I want put wrong answering to the Questions that i was during registration if i give wrong answers to the questions then a Email Notification should be trigger to Users.
    Regards
    Anil Kumar

    Hi Sylvain,
    I did all thing as you told me.First i created Criteria based Set after this we created a Workflow type Action and Actvities Type Notifcation Email template and finally i called this Workflow in MPR as Set Transition and call Set that i was created below.and
    check Advance View of Set this gives
    <Filter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Dialect="http://schemas.microsoft.com/2006/11/XPathFilterDialect"
    xmlns="/Request[(Creator">http://schemas.xmlsoap.org/ws/2004/09/enumeration">/Request[(Creator = 'b0b36673-d43b-4cfa-a7a2-aff14fd90522') and (RequestStatus = 'Denied or PostProcessingError')]</Filter>
    But this is not working for me so please tell me where i am wrong.
    Regards
    Anil Kumar

  • Java Calculator, Minus & multiplication button gets wrong answer?

    import java.awt.event.*;
    import java.applet.Applet;
    import javax.swing.*;
    import java.awt.*;
    public class calc extends JApplet implements ActionListener
         JTextField input = new JTextField("");
         JButton numbers[] = new JButton[10];
         JButton add = new JButton("+");
         JButton equals = new JButton("=");
         JButton minus = new JButton("-");
        JButton multiply = new JButton("*");
        JButton divide = new JButton("/");
        JButton clear = new JButton("AC");
         int num1 = 0;
         int num2 = 0;     
         String oper = " ";
         public void init()
              setLayout(null);
              setBackground(new Color(227,131,125));          
              Design();
         public void Design()
              int x = 1;
              int y= 1;
              int wi = 10;
              int he = 50;
              input.setSize(250,30);
              input.setLocation(10,10);
              add(input);
              add.setSize(80,30);
              add.setLocation(280,50);
              add.addActionListener(this);
              add(add);
              minus.setSize(80,30);
              minus.setLocation(280,90);
              minus.addActionListener(this);
              add(minus);
              multiply.setSize(80,30);
              multiply.setLocation(280,130);
              multiply.addActionListener(this);
              add(multiply);
              divide.setSize(80,30);
              divide.setLocation(280,175);
              divide.addActionListener(this);
              add(divide);
              equals.setSize(80,30);
              equals.setLocation(190,175);
              equals.addActionListener(this);
              add(equals);
             clear.setSize(80,30);
              clear.setLocation(100,175);
              clear.addActionListener(this);
              add(clear);
              while(x<=10)
                   if (x==10)
                   numbers[x-1] = new JButton("0");
                   numbers[x-1].setSize(80,30);
                   numbers[x-1].setLocation(wi,he);
                   //numbers[x-1].setBackground();
                   else
                   numbers[x-1] = new JButton(Integer.toString(x));
                   numbers[x-1].setSize(80,30);
                   numbers[x-1].setLocation(wi,he);
                   wi = wi + 90;
                        if(x%3==0)
                             he = he + 40;
                             wi = 10;
                   numbers[x-1].addActionListener(this);
                   add(numbers[x-1]);          
                   x++;
         public void actionPerformed(ActionEvent act)
              int x = 0;
              while(x<10)
                   if(act.getSource().equals(numbers[x]))
                        if(x==9)
                             input.setText("0");
                        else                    
                        input.setText(Integer.toString(x+1));
                   x++;
              if (act.getSource().equals(add))
                   num1 = Integer.parseInt(input.getText());
              else if(act.getSource().equals(equals))
                   num2 = Integer.parseInt(input.getText());
                   input.setText(Integer.toString(num1 + num2));
                   if (act.getSource().equals(minus))
                   num1 = Integer.parseInt(input.getText());
                   oper = "minus";
              else if(act.getSource().equals(equals))
                   num2 = Integer.parseInt(input.getText());
                   if(oper.equals("minus"))
                        input.setText(Integer.toString(num1 - num2));
                   if (act.getSource().equals(multiply))
                   num1 = Integer.parseInt(input.getText());
                   oper = "multiply";
              else if(act.getSource().equals(equals))
                   num2 = Integer.parseInt(input.getText());
                   if(oper.equals("multiply"))
                        input.setText(Integer.toString(num1 * num2));
    The addition button is working, but i cant seem to make minus and multiply button work, they get wrong answer when i use them.. what could bee the problem with my code

    Sorry, but I don't see a simple fix in this code here (Hopefully I'm wrong and someone else will see this, but I don't) Because of this, I recommend that you fully scrap this code and start over from square one. I don't think that you really "see" your logic here. To help you see what you are trying to do, you need to separate your logic from your GUI. Try to build a non-gui calculator that works via simple console menu. Once you get this working, then use this code to create a GUI calculator.

  • Why sun leader do not think about  "Why Java Web Start not be used widely"

    {color:#ff0000}Why sun leader do not think about "Why Java Web Start not be used widely"
    {color}
    Java Web Start was instruduced in jdk1.2, it's about ten years ago,But it's still not widely used--WHY?
    it's not because the design, it's becasue the code--the garbage code-- even the last version not work in many user computers,
    just not work suddendly -- noboday know reason--- if you do not believe, please google internet, many people suffered and suffering from web start!
    It's incredible that a famous big company like sun can not resolve an deployment problen in ten years that some very small company can do good work in much more short time !!!
    That' sun-- always say and design good things, then publish trouble and pain to their users. I really do not know what the sun's engineers are doing in so
    many years! -- why they do not know deployment is so important than others -- if deployment work fine, then the wrong thing can be correct easy !
    Sun, please do an famous big company -- give happy to user rather than pain !!! Please give us -- your users an stable and fast java web start to save us.
    {color:#ff6600}(Note: I use java web start to depoly our application, then receive endless complains, not work, slow and so on. now, we has no way just to give it up--design ourself's deployment-- that's also done by many pained people---just google it){color}
    Here is an desing suggestion:
    Client-end should be simple and stable, should let the server-end do complex thing .(now sun do opposite thing, they make Client-end complex, but server simple) ---it's because that Client-end will take widely effect on user's computer. update a few server is much more easy then update a amount of clients!
    Edited by: Jethro-Soft on Jun 30, 2008 8:49 PM
    Edited by: Jethro-Soft on Jun 30, 2008 8:52 PM

    Please check:
    http://joust.kano.net/weblog/archive/2006/04/06/why-i-will-never-deploy-with-java-web-start-again/
    http://kylecordes.com/2006/04/08/auto-update-no-web-start/

  • Reviewing Slides On Wrong Answer?

    When in questions is there a way of reviewing previous slides when a wrong answer is given; for example:
    A standard presentation of 50 slides is viewed and then candidates are taken to the question slides
    If question 1 is answered correctly it moves onto question 2
    if question 2 is answered incorrectly the candidate is then taken taken to the relevant slide (say slide 30) and returned to question 2 for another attempt.
    The only way I have managed to do this so far is to do a slight workaround by changing the way the reporting works i.e. duplicating the relevant reiew slides and putting them after the question slides.  Unfortunately this means the only way I can record their scores is to show quiz attempt not the native scoring results because on each review (out of the quiz) it resets the scores and shows an overall quiz fail for each wrong answer.  This obviously isn't the correct way of reporting quiz scores i.e.
    Number of questions set
    Incorrect answers
    Correct answers
    Percentage
    Pass/Fail
    This means that using this workaround I'm not getting the level of reporting normally available
    So my question is simply, is there a proper way I can record the correct scores and still retain the ability to review wrong answers?  This approach encourages a pro-active way to learn instead of penalising people for incorrect answers and allows them to learn without having to sit through a long presentation more than once - hence me wanting keep this style and be able to get full featured reporting.
    I apologise if I'm being a little long-winded in my explanation or indeed if I'm missing something pretty basic with the software.
    Many thanks in advance for anyone that may be able to help me with this
    Kind regards
    Martyn

    Hello Martyn
    Do not know if this has anything to do with etiquette, just did not know if you were asking me or the other user more help.
    As we both explained: with the Question slides that are in CP (will call them the default Quiz slides) this will not be that easy. You will have to give a lot of attempts for the Quiz to the user to make this possible. There is no way to change the system variables that store the score (such as cpQuizInfoTotalProjectPoints). If you want to realize your workflow you need to construct the Question slides yourself. That is why I offered some articles I published about this subject in CP5.
    You are not the first to ask for this kind of workflow, plan to work out an example but that will not be done today because of other priorities (some exams to be graded are waiting for me). The idea in steps is:
    Create your question slides using non-interactive objects like text captions, images and interactive ones buttons, text entry or click boxes (that get a score); this will not be possible for all kind of Question types, dragging p.e. as for matching or sequence questions is not possible, hotspot is possible.
    Be sure that all slides (to be reviewed before giving a second answer after an incorrect answer) are in the quizzing range (between first scored 'thing' and the score slide)
    On incorrect answer, create an advanced action that jumps to the slide(s) to be reviewed; on finishing those slides have an action that returns them to the question slide.
    On re-entering the question slide, re-initialize the score (to 0 if there is no 'penalty' because of the review) so that the user can answer again.
    Is this the workflow that you want? Which kind of question slides are you using? Is there a 'penalty' if the review possibility is used, I mean is the score that can be obtained lower than the first one?
    Lilybiri

  • Why java allow start() method only once for a thread

    Hi ,
    Why java allows start method only once for thread . suppose
    Thread t = new Thread();
    t.start();
    say at later stage if again we call t.start() IllegalStateException is thrown , even though isAlive method returns false.
    Hence the question , why start() method is allowed only once.If you need start a thread , we need to create a new instance.

    Really. Why do you think that? Do you have any evidence? It is one of the first things I would think of, personally.Considering that the Thread API doesn't allow you to specify a stack address (only stack size), I think it demonstrates they wanted to remove that capability from their Thread API all together. That missing "capability" makes me believe they want me to believe it's not something I need to worry about when using their API... I think the exact semantics of the Thread class and its methods were driven by how to make it most understandable and usable for their customers. I'm certain this issue was one of many that was given considerable thought during the design and implementation of the JVM and the underlying runtime classes.
    Do I have any evidence? No. But if you can point me at some first-hand information on this, I'd love to read it. Most of what I've found is second or third hand accounts. (and I mean that sincerely, not as a smart-ass remark or rebuke of your comments).
    On the one hand you seem to think the Java API designers are idiots, on the other hand you think that they should be. I can't make it out.I thought my position was that the Java developers were talented enough to implement platform in whatever way their API called for; hence, the designers made a choice about how they wanted their API to be used by their customers. They decided which capabilities they wanted to include or exclude, and created an API that was consistent with their vision for this technology. While I'm certain technical limitations had an effect on the API design, I certainly don't think the API was dictated by the them.
    I think the current design of the Java Thread API was a reflection of their vision to make Threading easier and more accessible to Joe Programmer, not limitations in the implementation. I never said it was wrong or that I could do better... I just said I think they could have done something different if they decided it would have made for a better customer experience. But hey, maybe I'm wrong.

  • Why Java is  following Unicode & not ASCII standard?

    Hi all,
    I am new to Java as well as to this forum.
    Could you please tell me why Java is not following ASCII format?
    And why is it following Unicode?
    Thanks,
    Reni

    Unicode is chosen because it's an abbreviation for Unique Ode, which means that it provides a special sort of poetry to give Java an aura of mystique, intelligence and worldliness that sets it apart from other languages.
    To support languages and characters other than English.Who doesn't read/speak English, really?! And why isn't there multiple language keywords for Java. Why can't I write code en Espa?ol?
    p?blico vac?o hagaAlgo(Secuencia s) {
       para(nent i = 0; i < s.longitud(); i++) {
          Sistema.fuera.impresi?nL?nea(i + " = " + s.car?cterEn(i));
    }(int abreviated for "n?mero entero")
    Message was edited by:
    bsampieri

  • Why java is called as true object oriented language?

    HI Friends,
    Though few oops concepts is not supported , why java is called as truly object oriented language and C++ as not a purely object oriented language???? Please, if any one know , give me the answer.
    Thanks to all.

    few oops concepts is not supportedwhich concepts?
    as far as i know...to be OO, you must supports
    encapsulation, abstraction, inheritancxe, composition (aggretration, et all) and polymorphism. Java supports all those comcept..now..Java is a hybrid due to what Jverd has pointed out.
    the only pure OO language that i know of is SmallTalk. they have Meta class that can create Class object. and all their primitaives are object.
    C# comes close, but their Class are not object.

  • Why java is called platform independent

    Hello
    Why java is called as platform independent?Any body please give a detailed explanation since im a beginner to java technology.
    ThankYou
    Jk

    BigDaddyLoveHandles wrote:
    georgemc wrote:
    SunFred wrote:
    Java is not platform independent since it depends on the Java platform ;)Don't complicate matters!I always thought the phrase should have been "platform agnostic"It's a phrase I've used meself

  • SSAS Tabular - Why is it wrong to call classify it as MOLAP, ROLAP or HOLAP?

    Hi There,
    I am working on an assignment (for a masters degree) in which I am evaluating different OLAP tools, and one of the tools assigned to me is Microsoft's BI stack.
    One of the classifications we are working on is whether a tool is MOLAP, ROLAP or HOLAP. When reading about SSAS Tabular, however, every single thing I read points out that SSAS escapes this traditional classification.
    I am trying to understand why would it be wrong to attempt to classify a Tabular instance of SSAS in such way? Why not say that SSAS Tabular is MOLAP, when using DirectQuery it is ROLAP, and if mixing both it is HOLAP?
    What is so fundamentally wrong about it?
    EDIT: Ah, and how does the Microsoft BI Semantic Model
    fits into the picture -- I assume is has something to do with the Tabular model being outside the traditional MOLAP/ROLAP/HOLAP classifiction?
    Thanks in advance for your help!
    Regards,
    P.

    Hi Pmdci,
    According to your description, you are looking for the reason why is it wrong to call classify SQL Server Analysis Service Tabular as MOLAP, right? As you know in MOLAP, data is stored in a multidimensional cube. The storage is not in the relational database,
    but in proprietary formats. And in ROLAP, data stored in the relational database to give the appearance of traditional OLAP's slicing and dicing functionality. However tabular solutions use relational modeling constructs such as tables and relationships for
    modeling data, and the xVelocity in-memory analytics engine for storing and calculating data. So as per my understanding, we cannot classify tabular as MOLAP.
    Reference:
    MOLAP, ROLAP, And HOLAP
    Comparing Tabular and Multidimensional Solutions (SSAS)
    Regards,
    Charlie Liao
    If you have any feedback on our support, please click
    here.
    Charlie Liao
    TechNet Community Support

  • Why java does not force to declare atleast one abstract method

    hi,
    i can define an abstract class without declaring any abstract method in that class. But why wud i do this ? i mean when i have decided that a particular class should be inherited by other subclass and subclass should porvide implementation then there should be atleast one method in the abstract super class which requires implementation.
    All i want to know is why java does not force to declare atleast one abstract method in abstract class.
    there may be some situations where this restriction can create problem if it is like that then can anybody give some example.
    manish

    hi,
    i didn't get u.
    u r trying to say that i have an abstract class with
    only static methods then my questions is why wud
    declare such a class as 'abstract' class? because a
    static method can't be abstract also. Even then if
    somebody want to define such a class with only static
    methods then compiler should force him to declare
    atleast one abstract method which can be implemented
    by subclass, because as i said before if sumbody
    decide to define a class abstract then he wants that
    it should be inhereted but as u r saying a class with
    only static methods then it should not be an abstract
    class it can be a simple class.there's no functional reason, really... actually, factory-like classes are often defined the way Ceci described
    "abstract" only ensures that nobody can ever get an instance of that class (as a matter of fact, what would be the point of getting an instance, if no instance method exists ?)

  • Why Java doesn't allow to reduce the accessibility of a method du

    Why Java compiler does not allow to reduce the accessibility of a method during inheritance?
    ( Eg; If the base class has a public method and if that method is overridden in child class but
    with defuault access, it gives compile error)
    Supposed answer:
    Because in the runtime, it cannot check the access modifier.
    Suppose A is the base class. It has a method fun() as public.
    B is the derived class of A.
    Suppose in some other class (say C) there is a method myFun() which takes A as parameter and
    calls the fun() method of A. So that method can take B
    also as parameter (As it is derived from A).
    So if the fun() method's accessibility is reduced in B, whether "that can
    be called in C or not" is not known. that is why compiler does not
    allow the reduce the accessibility of a method during inheritance.
    Member variables do not have this problem as they can be checked at
    compile time.
    Is this explanation correct?

    You can give private access, sort of... you could fake it, if the goal is to prevent someone from doing what the method does. Of course, they could (as long as A isn't abstract) create their own A and do whatever they want.
    class A {
       public void doThis() {
    class B extends A {
       public void doThis() {
          // explicitly do nothing
    }But I think generally, this shouldn't be a problem. I'm not sure if it's something that is common for creating an API to subclass another class to hide the superclass's methods. Usually you are adding functionality to a subclass that is for more specific things then the superclass supports. I mention creating an API because if it's just for some application class, then you are writing it, so use or not use the methods as you want. It's APIs for library type classes that other people would use, and if you are extending the library, and really need people not to call methods for some reason, document it. Maybe a good place for an assertion?

Maybe you are looking for