# How to convert a negative value to positive

Discussion in 'C Programming' started by Angus Comber, Nov 27, 2004.

1. ### Angus ComberGuest

Hello

Sorry this really is a newbie question!

I am doing some floating point arithmetic and calculating the time
difference between two dates. The date values being comparied are actually
double values. I was going to compare the dates by calculating the
difference betwen the two numbers. But sometimes you get a -ve and
sometimes a +ve value. I want to disregard a small variance eg of up to two
minutes but what is best way to compare values.

ie calculate difference and then convert any -ve values to +ve then check if
(diff > x)

or some other way?

AC

Angus Comber, Nov 27, 2004

2. ### Gordon BurdittGuest

>Sorry this really is a newbie question!
>
>I am doing some floating point arithmetic and calculating the time
>difference between two dates. The date values being comparied are actually
>double values. I was going to compare the dates by calculating the
>difference betwen the two numbers. But sometimes you get a -ve and
>sometimes a +ve value.

The unary minus operator will convert a negative value to a positive one.

>I want to disregard a small variance eg of up to two
>minutes but what is best way to compare values.
>
>ie calculate difference and then convert any -ve values to +ve then check if
>(diff > x)

You may want to use fabs(), in code similar to this:
#include <math.h>
double x1;
double x2;
double delta;

... put values in x1, x2, and delta ...;
if (fabs(x1-x2) > delta) { ... too far apart ... ; }
else { ... pretty close ... ; }

Gordon L. Burditt

Gordon Burditt, Nov 28, 2004

3. ### glen herrmannsfeldtGuest

Angus Comber wrote:

> I am doing some floating point arithmetic and calculating the time
> difference between two dates. The date values being comparied are actually
> double values. I was going to compare the dates by calculating the
> difference betwen the two numbers. But sometimes you get a -ve and
> sometimes a +ve value. I want to disregard a small variance eg of up to two
> minutes but what is best way to compare values.

Personally, storing dates as floating point seems
very strange to me. Yes, time is continuous(*), but not the
way it is usually measured, and not the way you want it
measured.

(*) I believe it is still unknown if quantum mechanics quantizes
time or not.

-- glen

glen herrmannsfeldt, Nov 28, 2004