inf & nan for mpq

Nic Schraudolph nic at schraudolph.org
Mon May 31 11:46:32 CEST 2010


Thanks for the feedback Marc, you raise very good points!

> You say mpq_equal(nan,nan) returns true, but for type double,  
> nan==nan returns false.

> You would probably want extra functions like mpq_isfinite, in a  
> second step.

True. What I've implemented so far was simply the most straightforward  
way to do things; mpq_equal(nan, nan) = 1 then popped out as the one  
way to test for nan. You're right, it's different from double, so  
perhaps a better idea to return 0 here and implement functions like  
mpq_isnan, mpq_isfinite, and such.

> sgn and cmp don't make much sense for nan, so a convention like 0  
> sounds ok to me. There is code out there that relies on sgn(x)==0  
> being equivalent to x==0, but then that code also relies on x being  
> finite... Not sure how much introducing inf and nan may confuse  
> existing code.


Yes. It's a good question: what should we do in such cases? If we want  
to be on the safe side, we should raise an exception. Or we have a  
convention like predicates always returning zero for nan and document  
that.

> By the way, with your patch, how does one test whether x==0?
> Creating a mpq to store 0 sounds like a waste, but sgn(x)==0 must  
> now come with !isnan(x) (yes, 3-valued comparison doesn't match well  
> with nan).

Yes, at present you'd have to do mpq_set_ui(zero, 0, 1); mpq_equal(x,  
zero) if you want to be sure you don't mistake a nan for a 0.

To put it in perspective though: the 5.0.1 code doesn't treat 0/0  
consistently either - some functions catch division by zero, but  
others interpret 0/0 as 0 instead, while others still crash with  
memory allocation and bus errors.

> You seem to have forgotten at least cmp_ui (I wouldn't have  
> commented, but you are calling the implementation "complete").

Yes, cmp_si as well I think. Thanks for catching that!

> The C++ wrapper would need modifications so that any comparison  
> involving NaN returns false.

Yes - haven't looked at the C++ wrapper at all yet. Raising an  
exception instead would save us the trouble.

> I guess a relevant benchmark would involve only small numbers (say  
> one or two limbs each), since that's where the overhead might be  
> noticable. Yes, that is a common use for mpq (though possibly not  
> what it is best suited for).

I've benchmarked & verified the code I've converted to mpq on the same  
problems it computed in long integers before, finding no significant  
difference in speed.

Cheers,

- nic





More information about the gmp-discuss mailing list