Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Equality checking for strings AND numbers

by Anonymous Monk
on Jul 15, 2007 at 06:37 UTC ( #626692=note: print w/replies, xml ) Need Help??


in reply to Equality checking for strings AND numbers

When comparing the numerical data for equality are you ever comparing numbers of different precision? If not why not just convert all data to strings and compare the string results. In deciding whether or not to cover the data you could use something like:

$string = to_string($string) unless is_string($string); (pulled from http://search.cpan.org/~dwheeler/Data-Types-0.06/lib/Data/Types.pm)

I am new to this so this is just a thought.

  • Comment on Re: Equality checking for strings AND numbers

Replies are listed 'Best First'.
Re^2: Equality checking for strings AND numbers
by mjscott2702 (Pilgrim) on Jul 15, 2007 at 23:41 UTC
    The problems here is that all of the numbers (ints and reals) do have different precisions - 10.0 and 10.00 are numerically equivalent, but are different when treated as strings.
      Check this page out, It has tests to find variables types, and how to convert them. You can test if a value is an int, if it is convert it to a real and then do the comparison.

      http://search.cpan.org/~dwheeler/Data-Types-0.06/lib/Data/Types.pm.

      With this you should be able to get it to at least the same variable type. If both become float types and and you compare 10.0 to 10.00, you should end up with equality... Another though that you can do is set up a tolerance for precision on number comparisons;

      Instead of if a == b

      do if (absolute value of (a - b)) > .0001 then .....

      Just some thoughts. I personally haven't done a lot with Perl yet.

      I'd argue that if you're bothering to mention precision at all, then 10.0 != 10.00.

      10.0 is really "somewhere between 9.95 and 10.05", and 10.00 is really "somewhere between 9.995 and 10.005". So if your 10.0 is really 9.97, it can't possibly be equal to 10.00.

        I guess it all comes down to how precise you want equality test to be in this program. If you want exact on the money the only way to get that I have ever seen is to do a direct string comparison as mentioned above. In this case 10.0 != 10.00. The reply to this suggestion before was that (10.0 == 10.00) evaluated to true. So it comes down to the basic question that has been asked throughout this post

        "How Precise do you want the numeric comparison to be?"

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://626692]
help
Chatterbox?
[choroba]: The issue created

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (9)
As of 2018-04-27 09:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?