Math Is Fun Forum

  Discussion about math, puzzles, games and fun.   Useful symbols: ÷ × ½ √ ∞ ≠ ≤ ≥ ≈ ⇒ ± ∈ Δ θ ∴ ∑ ∫ • π ƒ -¹ ² ³ °

You are not logged in.

#1 2009-01-18 17:05:31

MathsIsFun
Administrator
Registered: 2005-01-21
Posts: 7,713

Little Gems

Ever have little programming gems?

My example:

Instead of code like this to make sure an angle is between 0 and 360:

while (angle>360) {
    angle -= 360;
}
etc...

You can use this "little gem":

angle -= round(angle/360 - 0.5)*360; // this little gem makes sure angle is >=0 and <360

"The physicists defer only to mathematicians, and the mathematicians defer only to God ..."  - Leon M. Lederman

Offline

#2 2009-01-19 06:57:39

random_fruit
Member
Registered: 2008-12-25
Posts: 39

Re: Little Gems

Be careful!  If the type of 'angle' is an integer, the real maths involved in the second example can result in a loss of accuracy.  What may be better for an integer, might be to take the value modulo 360.  Also, the first piece of code does nothing where the value of the angle is already less than zero.

Offline

#3 2009-01-19 08:17:54

Ricky
Moderator
Registered: 2005-12-04
Posts: 3,791

Re: Little Gems

So the "gem" should be written as:

angle -= round(angle/360.0 - 0.5)*360; // this little gem makes sure angle is >=0 and <360

Noting the ".0" on the first 360.

Also, the first piece of code does nothing where the value of the angle is already less than zero.

Actually, I'm pretty sure the first piece of code won't run.  I don't think "etc..." is a proper function call. big_smile


"In the real world, this would be a problem.  But in mathematics, we can just define a place where this problem doesn't exist.  So we'll go ahead and do that now..."

Offline

#4 2009-01-19 09:13:37

MathsIsFun
Administrator
Registered: 2005-01-21
Posts: 7,713

Re: Little Gems

random_fruit wrote:

Be careful!  If the type of 'angle' is an integer, the real maths involved in the second example can result in a loss of accuracy.

True, depending on language. But in pseudocode it works perfectly cool


"The physicists defer only to mathematicians, and the mathematicians defer only to God ..."  - Leon M. Lederman

Offline

Board footer

Powered by FluxBB