Project

General

Profile

Actions

Feature #10425

open

A predicate method to tell if a number is near another

Added by sawa (Tsuyoshi Sawada) over 9 years ago. Updated over 9 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:65898]

Description

A method near? like the following would be useful.

class Numeric
	def near? other, delta: Float::EPSILON
		(other.to_f - to_f).abs <= delta.to_f
	end
end

class Time
	def near? other, delta: Float::EPSILON
		to_f.near?(other.to_f, delta: delta)
	end
end

It can be used to check errors, or whether something is around something.

23.24324.near?(23.23, delta: 0.5) # => true
t1 = t2 = Time.now
t3 = Time.now
t1.near?(t2) #=> true
t1.near?(t3) #=> false
5.near?(3, delta: 1) #=> true

Some testing frameworks have something similar to this, but I think this is an elementary concept that Ruby should support at it core.


Related issues 1 (1 open0 closed)

Related to Ruby master - Feature #15811: Propsing new method for comparing equality of 2 (float) numbers relativelyOpenActions

Updated by sawa (Tsuyoshi Sawada) over 9 years ago

The definition above is just to illustrate the functions. There may be a better implementation. Especially, an appropriate error message should be given when an inappropriate argument is given.

error might be a better name to replace the named parameter delta. I am not sure.

Updated by duerst (Martin Dürst) over 9 years ago

Such a predicate would indeed be convenient. But sometimes, one doesn't want to compare with an absolute epsilon, but relatively, e.g. like so:

((other.abs.to_f + abs.to_f) / (other.to_f - to_f).abs) <= ????

Actions #3

Updated by mame (Yusuke Endoh) almost 5 years ago

  • Related to Feature #15811: Propsing new method for comparing equality of 2 (float) numbers relatively added
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0