Mathematical calculations using BigDecimal

Hi all,
I am doing some mathematical calculations using float variables. They are not working properly because of rounding issues....So, before I change the whole program to do the same calculations using BigDecimal, just wanted to check out whether there are any catches in that also. Like, is it safe if I do BigDecimal.add, subract etc. instead of addding the floating point numbers directly.....Can I be assured that the results will be precise, to 2 decimal places?
Any help will be appreciated...
Thanks

The "catch" is that computers do not work with real numbers. They work with representations of real numbers like finite decimals or fractions. My advice is to continue to use doubles, but do not expect infinitely precise results and round the values when outputting them.

Similar Messages

  • Mathematical calculation with out using operators

    i am beginer of java.my sir was asked to try out problem.
    perform mathematical calculation without using arthematic operators.

    How about this example:
    import java.math.BigInteger;
    public class MathWithoutOperators {
        public static void main(String[] args) {
            BigInteger x = new BigInteger("12");
            BigInteger y = new BigInteger("54");
            BigInteger z = x.add(y);
            System.out.println(z.toString());
    }See the API documentation of class java.math.BigInteger for more.

  • Mathematical calculations in ABAP Query

    Dear gurus
    Can I perform mathematical calculations in ABAP Query?
    Kingly guide
    MK

    Hi
    You would need tables - AFPO, AUFM, MSEG, MAKTX (if you need mtl description).
    Use AFPO table to pass your FERT material number, then read the order numbers for this order.
    Now in AUFM there is an Index on AUFNR field, so you can pass all the order nos. of the FERT to this field.
    If you want to limit for a certain period, then use AUFM-BUDAT which is the posting date.
    Now add all the 261 movements for which there is no 262 movement, you can check for reversals in MSEG table. This you can do per component & display the data as per your need.
    Regards,
    Vivek
    Added
    You can get this info in COOIS report as well, by selecting List option as Documented Goods Movement & by using suitable filter options.

  • Using bigdecimal class

    I was using Gregory-Leibniz series to calculate PI = 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ...
    Something like:
    double pi = 0.0;      
           int limit = 3000000;      
           for (int i = 0, y = 1; i <= limit; y+=2, i++)
                     if (y == 1)
                          pi = 4;
                   else if (i % 2 == 0)
                          pi += (double)4/y;            
                     else
                          pi -= (double)4/y;                                                   
                     System.out.println(String.format("Loop %d: %.20f", i, pi));                                    }Then I realized PI isn't going to be totally accurate according to IEEE Standard for Binary Floating-Point Arithmetic that java math calculation uses, so I was trying to use BigDecimal class (new to me), this is what I got initally...
             BigDecimal pi = new BigDecimal("0.00");           
              int limit = 3000000;
              for (int i = 0, y = 1; i <= limit; y += 2, i++)
                  if (y == 1)
                          pi = new BigDecimal("4.0");
                   else if (i % 2 == 0)
                          pi = pi.add(new BigDecimal( Double.toString( (double) 4 / y )));
                     else
                          pi = pi.subtract(new BigDecimal( Double.toString( (double) 4 / y )));
                        System.out.println(String.format("Loop %d: %s", i, pi.toString()));                                       
    I realize that when I do the 4/y calculations involving both doubles... the result is probably stored according to the IEEE standards which is the thing to avoid... Is that correct? Is my PI result going to be accurate?
    I noticed with this one decimals up to the 22nd place are all filled with some numbers in the calculations compared with the first one involving only double number calculations which had zero's starting around the 15th decimal.
    Something like doesn't work and ends up with arithmeticexceptions...
    pi = pi.subtract(new BigDecimal("4").divide(new BigDecimal(Integer.toString(y))));
    So I'm actually confused about the right way of using BigDecimal class in this type of calculation to get accurate results. I do realize it's an immutable class and probably a bad idea to use it like this 3 million times in a loop.

    quoting from the API documentation on BigDecimal
    "The BigDecimal class gives its user complete control over rounding behavior. If no rounding mode is specified and the exact result cannot be represented, an exception is thrown; otherwise, calculations can be carried out to a chosen precision and rounding mode by supplying an appropriate MathContext object to the operation."
    That explains the arithmetic exceptions.
    You would be advised to choose your scale first, (that would be the number of decimal places that you want to be using for your calculation. ) Then use the BigDecimal constructors that use the scale value. Construct your BigDecimal 4 outside of the loop so that you are not constructing it over and over again. And finally, read the documentation on how the scale of the result will depend upon the scale of the components going in.
    A little reading and possibly re-reading of the documentation will help in the understanding of the BigDecimal class.

  • Looking for examples using BigDecimal

    Two newbies to Java are looking for examples of code that use the BigDecimal features for rounding and truncating large numbers to more user-friendly values.
    We are doing some hefty math calculations on values defined as doubles and want to round and truncate to within 1/100th for display purposes.
    We've tried some stuff on our own, but it is not cooperating. Any help would be greatly appreciated!

    Here is a good article of how to use BigDecimal
    http://www.javaworld.com/javaworld/jw-06-2001/jw-0601-cents.html
    Hope this helps

  • Implementing a mathematical calculation

    Hello, I would appreciate help with implementing a mathematical calculation with pl/sql:
    For a specific number of times, say N, do the following:
    X/(1+ y) + X/(1+y)*(1+y) + X/(1+y)*(1+y)*(1+y) + ....... + X/(1+y)*(1+y)*(1+y)*(1+y)*(1+y)*etc, N times.
    X and y are known values of course.
    best regards
    Harald

    assuming you missed parens (as others assumed), and you really meant
    X/(1+ y) + X/((1+y)*(1+y)) + X/((1+y)*(1+y)*(1+y)) + ....... + X/((1+y)*(1+y)*(1+y)*(1+y)*(1+y)*etc, N times)
    then the answer is
    x* (1 - power(1+y,-1*n ) ) / y no recursion, no generating extra rows, just a simple equation
    the proof is:
    let's make z=1+y, so your equation becomes
    X/z + X/(z*z) + ....... + X/(z*z*z...)
    converting to exponents:
    X/z + X/z^2 + ....... + X/z^(n-1) + X/z^n
    remove X to the outside:
    X( 1/z + 1/z^2 + ....... + 1/z^(n-1) + 1/z^n )
    using negative exponents instead of the eternal "1/":
    X( z^-1 + z^-2 + ....... + z^(1-n) + z^-n )
    let's remove x for now, and just work on solving the inner summation, and call it S.  your answer will be x*S
    S = z^-1 + z^-2 + ....... + z^(1-n) + z^-n
    let's make a new equation by multiplying both sides by z
    zS = 1 + z^-1 + ....... + z^(1-n)
    now subtract the two equations
    zS - S = (1 + z^-1 + ....... + z^(1-n)) - (z^-1 + z^-2 + ....... + z^(1-n) + z^-n)
    simplify:
    zS - S = 1 - z^-n
    now solve for S:
    S(z-1) = 1 - z^-n
    S = (1 - z^-n) / (z-1)
    plug the definition of z back in:
    S = (1 - (1+y)^-n ) / ( (1+y) - 1 )
    S = (1 - (1+y)^-n ) / y
    now, let's not forget about X.  your desired answer is x*S
    or x* (1 - (1+y)^-n ) / y

  • Designing a calculator using selection screen(abap)

    hi i just now stepped into this technology. iam learning abap.  i like to jknow how to design a calculator using selection screen. 
    could any one give your  suggestions or any sites having such example programs . 
    thankyou

    Hi
    Welcome to SDN.
    Use the sample peace of code for design Calculator.
    Hi,
    Create push buttons for the + , - , / , * , = in your dialog program.
    Create an input field with the data type that can accept decimal places..
    When the enter 12 then press the push button "+" button store the value 12 in a variable v1..Then clear the input field..
    Then when the user enters another number..lets say "13"..
    Then if the user presses the "=" button...Then sum the values from the variable v1 with the input field..
    Hope this helps..
    Check this sample code..
    MODULE USER_COMMAND.
    CASE SY-UCOMM.
    WHEN 'ADDITION'.
    ASSUMING THE INPUT FIELD NAME IS P_INPUT.
    V_V1 = P_INPUT.
    V_OPERATION = '+'.
    CLEAR: P_INPUT.
    WHEN 'EQUALTO'.
    CASE V_OPERATION.
    ADDITION
    WHEN '+'.
    SUM UP THE VALUES.
    P_INPUT = P_INPUT + V_V1.
    ENDCASE.
    MULTIPLICATION
    WHEN '*'.
    MULTIPLY UP THE VALUES.
    P_INPUT = P_INPUT * V_V1.
    ENDCASE.
    ENDCASE.
    ENDMODULE.
    Regards,
    Sree

  • Interactive ROI Calculator using Flash Catalyst?

    Hello, a client of ours has asked us to create an interactive ROI calculator similar to the one in the following link:
    http://bit.ly/98vjCF
    Our design and production department does work in Flash, mainly to create simple web banners, however they're not hardcore Flash developers by any means. We'll be upgrading from CS4 to CS5 with Catalyst soon. Is it possible to create an interactive ROI calculator using this software or would using a seasoned Flash developer be a better choice?
    Thanks for any info.
    henry

    Hi Henry,
    You can use Flash Catalyst to design the UI of your calculator, both for protyping and optionally for final production too.  However, to do the actual calculations you'll have to write a bit of code using another tool.  For example, you can import the Catalyst project into Flash Builder and wire up the calculation logic to the UI you've created.  This gives you the option of having a nontechnical designer work on the UI, while a less design-oriented developer writes code without having to worry much about the visuals.
    The underlying code used in a Catalyst project is Flex 4.  This should be a snap for a seasoned Flash developer to work with.  Or, a Java or JavaScript developer should also be able to get up to speed on Flex pretty easily (especially if the UI was already built in Catalyst and the dev is just wiring up the "business logic").
    Hope that helps,
    - Peter

  • Creating a ad-hoc calculation using sql query

    Hi All,
    I want to know if its possible some way to create a ad-hoc sql query inside a workbook so as to create a calculation using that sql.
    I have a folder which gives me balance for any period. My requirement is to display current period balance along with prior years closing balance in same record for each code combination. I dont want to modify folder definition.
    Thanks for your inputs.
    Vishal.

    You could try creating a custom function for this purpose. You would need to register the function in the End User Layer and then you can call the function from your report.

  • Calculations using Physical Tables vs Logical Tables

    It's easy to find an example of where you would want to use Logical Tables instead of Physical Tables to create fact columns in the repository. Any measure such as Profit Margin (i.e. Profit / Sales) must be computed in the Logical Tables, so that the division operation occurs after the dimensional aggregations are passed to it from the physical layer. In the example of (Profit / Sales), using Physical Columns returns an incorrect result, because it does the division operation first, then aggregates all of those results into a nonsense value.
    So, is there some type of formula in which the reverse is true, such that using Logical Tables would return an incorrect result, while the Physical Tables would return the correct result?
    If not, then under what circumstances would we want to use the Physical Tables instead of the Logical Tables? Is there some type of formula that performs better with Physical Tables?

    Hi Thomson,
    calculations using physical columns generate fair SQL which wouldn't involve any sub-selects in physical query... and would be fast.
    If you use logical columns by selecting the “Use existing logical columns as the source check box" in rpd, most of the times it generates queries.. with sub-selects (means subqueries)
    Ex: suppose you are calculating a calculation based on 2 columns a, b then
    If you use, Logical columns, the query would be something like...
    *Select D1.C1 + D1.C2*
    *From (select Sum(X) as C1,*
    *Sum(Y) as C2*
    *From FactX) D1*
    *Group by DimY*
    If you use, phyiscal columns for calculation the... the query would be...
    *Select Sum(D1.C1 + D1.C2)*
    *From FactX*
    *Group By DimY;*
    which is much preety and good to query the database... without any difficult..
    For first query... it's using inner queries... so process would be slow...
    +Thanks & Regards+
    +Kishore Guggilla+

  • Explain How delivery date is calculated using backward and forward schedul

    How can anyone please explain how delivery date is calculated using forward and backward scheduling
    I want to have it broken down into the following steps
    for eg for delivery date calculation following dates are used
    Material Availabilty Date
    Material Staging Date
    Pick/pack time
    Transportation PLanning date
    Loading date
    Goods issue date
    Transit Date
    Delivery Date
    Can some one please give me an example and explain wht these dates are
    for eg customer needs delivery date on  11/20/2008
    how would the system cacluate whether it can meet the delivery date using backward scheduling
    and if it doesnt meet how does the system do the forward scheduling
    also i am not clear with the following dates
    material avaialibilty date
    material staging date
    transportation date
    can some one please explain me all this in detail
    Thanks

    Hi,
    Basically this is the CRSD(Customer requested ship date logic)logic in which system calculates the ship date depends upon the material availability. If material is available system calculates ship date on the basis of master data maintained in customisation.Master data is maintained in the  following link.
    If material is not available then system takes into consideration vendor delivery date & then calculate customer ship date.
    Please go through the link in SPRO
    LE-Shipping -Basic shipping functions-Scheduling -Delivery scheduling & Transportation scheduling-Maintain duration.
    In customisation following data is maintained
    Material Availabilty Date
    Material Staging Date
    Pick/pack time
    Transportation PLanning date
    Loading date
    Goods issue date
    Transit Date
    Delivery Date
    Hope you got the idea of CRSD calculation
    Regards,
    Prashant.

  • Determine Number of Decimal Place using BigDecimal

    I was interested to have the following getNumberOfDecimalPlace function :
    System.out.println("0 = " + Utils.getNumberOfDecimalPlace(0)); // 0
    System.out.println("1.0 = " + Utils.getNumberOfDecimalPlace(1.0)); // 0
    System.out.println("1.01 = " + Utils.getNumberOfDecimalPlace(1.01)); // 2
    System.out.println("1.012 = " + Utils.getNumberOfDecimalPlace(1.012)); // 3
    System.out.println("0.01 = " + Utils.getNumberOfDecimalPlace(0.01)); // 2
    System.out.println("0.012 = " + Utils.getNumberOfDecimalPlace(0.012)); // 3
    I use the following code
        public static int getNumberOfDecimalPlace(double value) {
            final BigDecimal bigDecimal = new BigDecimal("" + value);
            final String s = bigDecimal.toPlainString();
            System.out.println(s);
            final int index = s.indexOf('.');
            if (index < 0) {
                return 0;
            return s.length() - 1 - index;
        }However, for case 0, 1.0, it doesn't work well. I expect, "0" as result. But they turned out to be "0.0" and "1.0". This will return "1" as result.
    0.0
    0 = 1
    1.0
    1.0 = 1
    1.01
    1.01 = 2
    1.012
    1.012 = 3
    0.01
    0.01 = 2
    0.012
    0.012 = 3
    Any solution?

    Please [don't cross-post!|http://stackoverflow.com/questions/2296110/determine-number-of-decimal-place-using-bigdecimal], it's considered rude. If you must do it, then at least link each post so that people can find out which answers you've already got in order to avoid duplicate work on our part.
    Please read [_How To Ask Questions The Smart Way_|http://www.catb.org/~esr/faqs/smart-questions.html].

  • Calculator using swing

    hello everyone,
    I am new toprogramming and alst to java language. can anybody help me in writing calculator using java swing.
    the functionality of the calculator should be same as the one we use in windows operating system
    please help me

    please help meSure, what problem to you have?
    if you are starting from scratch, get a copy of this book
    http://www.amazon.com/gp/product/1931841608/qid=1144486744/sr=2-1/ref=pd_bbs_b_2_1/002-4043290-4676869?s=books&v=glance&n=283155
    which builds a calculator throughout the book

  • I cannot enter numbers in my calculator using the keypad - only using the mouse - anyone know why?

    I can't enter numbers into the calculator using the keypad - however I can use the calculator with the kwyboard numbers or the mouse using the nu,mbers on the calculator.  In preferences, - keyboard - it says  that the F6 key toggles the num lock system - on my computer the F6 key does nothing.  I am running Snow Leopard, haven't downloaded Lion yet.  Anyone help me with this?
    Paul

    using OS 10.6.8 - INtel Core 2 Duo, keyboard is wired (USB) came with computer, cpmputer purchased in January 2006 - I have not tried using it in other apps - just tried it in Quicken, and Quicken froze requiring force quit.  Generally only use it for manually making check-book entries.  I know that in the past I have used the keypad - tho I admit it has beena while

  • Exponentail operations using BIGDECIMAL

    hi all
    Can u someone provide me links, notes, codes and suggestions to perform exponential operations using BigDecimal.
    Thankz in advance
    Arun :)

    If you require greater precision than double provides
    and your exponent is integer try
    Google [
    [url=http://www.google.com/search?hl=en&ie=UTF-8&q=squa
    e+and+multiply&btnG=Google+Search]square and
    multiply ]Good point. I forgot the obvious. m^2 = m * m, etc.

Maybe you are looking for

  • Dataloss in network... How to trace it..?

    Hi, Though this question is related to SAP XI and SMICM trace, I feel this question can also be answered by people in WebAs General, so i am posting this in this forum. In my current scenario where SAP XI system pushes data to another system(ABC syst

  • Will I be able to use Mountain Lion

    I have a macbook pro 4,1. and have been seeing possiblities that I may not be able to run Mountain Lion.  Does anyone know?  I purchased my machine in March 2008.  It is Intel  core 2 duo and currently run Snow Leopard.  I just pruchased an iPhone an

  • How to find out that position is a chief position or not?

    Hi All, Kindly let me know to find out the position is a chief position or not? I have to display various positions with Y if it is a manager and N if it is not. Thanks! Sachin

  • Word Processing with an IPad 2

    Hi all! I just got an iPad 2 (WiFI, 32GB) and want to write some documents on it. I know I can read word documents on the iPad, but how can I create and save them? I apologize if this question has previously been answered, but I've been looking much

  • Ipad Video app closes

    Currently i cannot play any movies on my ipad and i cannot figure out what is wrong. The Videos app on my ipad shows the movies i transferred over from Itunes by USB connection.  If i click on any movie i get to the individual movie page that shows t