M.J.Watson
M.J.Watson

Reputation: 480

Find all the times which has angle 0 in java

I am trying to print all the times has zero angle between hour and minute. Also seconds is important here too.

My output is

0:0:0

12:0:0

,but i want output like these

0:00,

1:05.45

public void FindZeroAngle ()
        {
            int seconds =00;
            int minute=00;
            int hour= 00;
            for(int i=0; i<86400 ;i++)
            {
                double h_angle= (30*hour)+ 0.5 *(minute+seconds/60.0);
                double m_angle =((6.0*minute)+(((1/60.0)*6)*seconds)); 
                double angle=m_angle-h_angle;

                if (angle<0) angle=-angle;
                if(Math.min(360-angle,angle)==0)
                {
                    System.out.println(hour + ":" + minute + ":" + seconds);
                }

                if(seconds !=60)
                    seconds++;

                if(seconds==60)
                {
                    seconds=0;
                    minute++;
                }

                if(minute==60)
                {
                    hour++;
                    minute=0;
                    if(hour==24)
                        hour=00;
                }

            }

What is the problem in my code?

Upvotes: 1

Views: 69

Answers (2)

Chexxor
Chexxor

Reputation: 416

You already figured your problem is related to double precision and non-exact answers. Now the first solution that comes to my mind is something similar to "Prune and Search"'s concept. And that concept is to check for the transition from positive to negative angular difference, or vice versa.

In detail:

Boolean hasIntersected = false;

[...] //Do some calculation of angle between minutes/hours. keep the sign, i.e. negative before intersection.

//Assuming that there's one intersection each hour, we reset the boolean every hour
if(minutes == 0 && seconds == 0)
    hasIntersected = false;

if(!hasIntersected && angle >= 0){
    hasIntersected == true;
    System.out.println("Output timestamp here or something");
}

angle >= 0 meaning the minutes has passed/is passing the hours in this example, can be opposite depending on how u calculate the angle.

By checking for when the minutes passed the hour instead of checking for when it hits the hour you get along pretty precise, down to the second when you run this each second. However it will round up to the next second if it lands between seconds.

Upvotes: 1

Adi Levin
Adi Levin

Reputation: 5243

You're sampling only times at 1 second intervals. The precise answers don't have integer-valued seconds, except at 00:00 and 12:00.

Upvotes: 2

Related Questions