java - problem with a data structure
I created a code in my spare time that prints out the entire fibonacci sequence. But, at the ninety-third number, it turns negative. I think that this is because I'm declaring the number as a long. Is there any other primative data structure that can hold REALLY large numbers?
0
Comments
*Breaks out Java Book*
you could use double, it is good to ~1.79xxx+308. You could use that and truncate the decimal early on if you do not need/want it.
float it's approximate range is + or - 3.4 x 10^38
float's precision is at least 6 decimal digits.
double it's approximate range is + or - 1.8 x 10^308
double's precision is at least 15 decimal digits.
Those should help you out with what you need.
list of all java data types.
You could output as a string. or write to a text file and grab it from there and display that way.
btw above solutions would not make it in sci notation automatically
are you using a gui, or just the console?
[PHP]
import java.math.*;
public class TestBig {
private static final int Fractional_Digits = 50; //
private static final int N_Terms = 200; //
static final BigDecimal golden_ratio = new BigDecimal("1.618033988749894848204586834365638117720309179805762862135448622705260462818902449707207204189391138");
public static void main(String[] args)
{
BigInteger lo = BigInteger.valueOf(1L);
BigInteger hi = BigInteger.valueOf(1L);
int n = 1;
System.out.print(n);
System.out.print("\t");
System.out.println(lo);
while (n < N_Terms)
{
n++;
System.out.print(n);
System.out.print("\t");
System.out.print(hi);
System.out.print("\t");
BigDecimal ratio = new BigDecimal(hi);
BigDecimal den = new BigDecimal(lo);
ratio = ratio.divide(den, Fractional_Digits, ratio.ROUND_HALF_DOWN);
System.out.print(ratio);
System.out.print("\t");
System.out.println(ratio.subtract(golden_ratio).setScale(Fractional_Digits,
ratio.ROUND_HALF_DOWN));
hi = lo.add(hi);
lo = hi.subtract(lo);
}
}
}
[/PHP]
--edited
sorry, posted the wrong sample earlier. I realize this prints sceintific notation and i forgot you didn't want that. hmm. check the API, perhaps there's a different format or you could simple use a pad function.
[PHP]
import java.math.BigInteger;
public class TestBig {
public static void main(String[] args) {
BigInteger low = BigInteger.ONE;
BigInteger high = BigInteger.ONE;
for (int i = 1; i <= 200; i++) {
System.out.println(low);
BigInteger temp = high;
high = high.add(low);
low = temp;
}
}
}
[/PHP]