java - Floating point errors -


I'm having trouble with floating points in a double Java 56, for example, in fact .56000 Can be archived ... 1.

I am trying to convert a decimal to a fraction. I tried to use it for continuous fractions

But using my method, my answers were wrong because the computer was stored and scored in decimal How it is done.

I tried the alternative method:

  public static rational rational (double A) {if (A> = 1) {// throw exceptions} string copOut = Double.toString (a); Int counter = 0; Println (a); While (a% 1! = 0 & amp; Counter & lt; copOut.length () - 2) {a * = 10; Counter ++; } Long deno = (tall) math.paw (10, counter); // Neniminary Rational Frac = new rational set (long) A, Dano) // Unusual logical number long GCD = FRCCCC (); Long fnum = frac.getNumer (); // very faden = frac.getDenom (); // becomes divisor = new rational (fnum / gcd, fden / gcd); Come back; }  

I use the string to find the decimal length to determine how many times by 10 times. I later reduced the decimal. It gives me the right answer, but does not feel like the right approach? Can someone suggest 'right' ways to do this?

Actually you are doing great .. but this will fail if input 11.56 < There is something about / code>. Here you have to do copOut.length () - 3 .

To use this dynamic, use string # partition ()

  string dcLambon = copOut.split ("\\.") [1 ]; // as a result "56" (the actual string after the decimal)  

Now you only have to do

  (while a% 1! = 0 & Amp ; Amp; counter & lt; decLength.length ()) {one * = 10; Counter ++; }  

If you want to delete the loop, use

  long D = (tall) Math.pow (10, decLength.length ()) Do; One a * d =;  

Comments

Popular posts from this blog

ios - How do I use CFArrayRef in Swift? -

eclipse plugin - Run java code error: Workspace is closed -

c - Error on building source code in VC 6 -