Results 1 to 2 of 2
Like Tree1Likes
  • 1 Post By jim829

Thread: fibonacci iterative - calculating wrong

  1. #1
    Gatsu is offline Member
    Join Date
    Dec 2012
    Posts
    42
    Rep Power
    0

    Default fibonacci iterative - calculating wrong

    Hello, I have a textfile with the correct 100 steps of the fibonacci sequence which I am trying to match with what my code calculates but at step 82 it does not calculate the correct value, would somebody know why it does like that?

    Java Code:
    //@param number Number of steps to calculate
    public Double produce(int number)
    	{
    		double reSult = 0;
    		
    		double one = 0;
    		double two = 1;
    		double three = 0;
    		
    		if(n <= 1)
    		{
    			fibNum = number;
    		}
    		else
    		{
    			for(int i = 2 ; i <= number ; i++)
    			{
    				three = one + two;
    				one = two;
    				two = three;
    				
    				reSult = three;
    			}
    		}
    		
    		return reSult;
    	}
    Last edited by Gatsu; 05-20-2013 at 09:54 PM.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,040
    Rep Power
    6

    Default Re: fibonacci iterative - calculating wrong

    Most likely it has to do with the floating point precision of doubles which can be inconsistent depending on the order of operations and a variety of other things. I suggest for items involving big numbers like Fibonacci sequences and factorials you use the BigInteger class.

    Regards,
    Jim
    Gatsu likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Fibonacci sequence using iterative and recursive method
    By baumboards in forum New To Java
    Replies: 5
    Last Post: 03-02-2011, 07:57 PM
  2. Iterative Preorder
    By hansmoolman in forum New To Java
    Replies: 4
    Last Post: 11-02-2010, 02:29 PM
  3. Help with while iterative procedure
    By SweetLD215 in forum New To Java
    Replies: 16
    Last Post: 10-20-2010, 07:54 AM
  4. Iterative help
    By Jnoobs in forum New To Java
    Replies: 5
    Last Post: 10-06-2010, 09:26 PM
  5. Iterative Algorithms
    By Zosden in forum Algorithms
    Replies: 1
    Last Post: 07-05-2008, 07:29 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •