www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/03/31/11:35:22

Date: Tue, 31 Mar 1998 18:32:31 +0200
From: Hans-Bernhard Broeker <broeker AT physik DOT rwth-aachen DOT de>
Message-Id: <199803311632.SAA20450@acp3bf.physik.rwth-aachen.de>
To: alanc AT clara DOT net (Alan Carter)
Cc: djgpp AT delorie DOT com
Subject: Re: ATAN causing FP Exception
Newsgroups: comp.os.msdos.djgpp
Organization: RWTH Aachen, III. physikalisches Institut B

In article <01bd5ca7$c0918ce0$395008c3 AT alan> you wrote:

[...]

> float get_ang(int x1,int y1,int x2,int y2)
> {
>     // return angle between 2 points in degs

>     float xlen,ylen,ang,res,sub;
>     res=sub=xlen=ylen=ang=0;

>     xlen=fabs(x1-x2);
>     ylen=fabs(y1-y2);

Up to here, all's fine, basically. Only exception: I can't see why
you'ld want to use *floats* here. Use *doubles* instead. On Intel
machines, that'll give you more precision in the same execution time,
roughly

>     res=xlen/ylen;

Here, the trouble starts. Whenever ylen is zero (not too improbable,
after all), this is a division by zero. It should cause an exception
already, but I'm not absolutely sure about that. Calculation the
atan() of the result of this operation is asking for trouble.

[...]

Anyway. Here's a free tip how to write this routine much more easily:

/* Just in case: don't ever omit this if you call math routines! */
#include <math.h>

float get_ang(int x1,int y1,int x2,int y2)
{
    float xdiff,ydiff

    xdiff=x1-x2;
    ydiff=y1-y2;

    return atan2(ydiff,xdiff) * 180 / M_PI;
}



--
Hans-Bernhard Broeker (broeker AT physik DOT rwth-aachen DOT de)
Even if all the snow were burnt, ashes would remain.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019