Search code examples
javainfinity

why i get infinity ? can it solved?


i have code like this, i try to get number from henon formula

public class henon 
{
    public static void main(String[] args) 
    {         
        double a = 0.3;
        double b = 1.4;    
        double k[] = new double[1026];
        k[0] = 0.01;
        k[1] = 0.02;              

        for(int i = 0; i < 1024; i++)
        {                       
            k[i+2] = 1 - (a * Math.pow(k[i+1], 2) + b * k[i]);          
            System.out.println( "nilai ke" + i +" adalah " + k[i]);
        }
    }               
}

how i can get infinity valuew in 24, 25 ...how to solve it?


Solution

  • BigDecimal is better for your requirement.

    double and float are not useful for accurate results as Joshua bloch said in Effective Java.

    BigDecimal k[] = new BigDecimal[1026];
            k[0] = new BigDecimal(0.01);
            k[1] = new BigDecimal(0.02);  
            for (int i = 2; i < k.length; i++) {
                k[i]=new BigDecimal(0.0);
            }
    

    if you want double value of Bigdecimal ,you can use doubleValue() method.