[Date Index]
[Thread Index]
[Author Index]
Re: Using ReplaceAll (/.) on numerical digits
*To*: mathgroup at smc.vnet.net
*Subject*: [mg113281] Re: Using ReplaceAll (/.) on numerical digits
*From*: Albert Retey <awnl at gmx-topmail.de>
*Date*: Thu, 21 Oct 2010 07:05:15 -0400 (EDT)
*References*: <i9m854$jr5$1@smc.vnet.net>
Hi,
> I found some seemingly weird behavior with ReplaceAll as shown below. Note
> how 0.563 in data remains untouched while 0.562 and 0.564 get replaced as
> intended, but when I simply type in 0.563 and do a replace, it gets replaced
> successfully. Can someone explain why this happens?
There is a difference in what something really is and what is shown in a
Notebook as the output, which is by default set to StandardForm. To see
what you really try to match, wrap your input with InputForm or
FullForm, which is always a good try when pattern matching doesn't work
as you expect. Here is what I get:
{0.5600 + 20/10000, 0.5600 + 30/10000, 0.5600 + 40/10000} // InputForm
{0.562, 0.5630000000000001, 0.5640000000000001}
It might be obvious what goes wrong by now (actually it is not clear to
me why the 0.564 case works here). The basic thing to learn is that
pattern matching on real numbers is usually a error prone thing to do.
Here is something that is more robust, since it uses the greater
tolerance of Equal when comparing numbers:
0.5600 + 30/10000/. x_ /; x == 0.563
for even more control you could use something like e.g.:
0.5600 + 30/10000/. x_ /; Abs[x,0.563]<10^-6
hth,
albert
> In any event, I've got a workaround based on StringReplace, which is likely
> safer whether the weird behavior is a bug or a misunderstanding on my part.
>
> data = 0.5600 + 1/10000 {20, 30, 40} {0.562, 0.563, 0.564} (* 0.563 stays
> untouched *) data /. {0.562 -> 0.5622, 0.563 -> 0.5637, 0.564 -> 0.5641}
> {0.5622, 0.563, 0.5641} (* 0.563 stays untouched *) (0.5600 + 1/10000 {20,
> 30, 40}) /. {0.562 -> 0.5622, 0.563 -> 0.5637, 0.564 -> 0.5641} {0.5622,
> 0.563, 0.5641} (* 0.563 stays untouched *) {0.5600 + 20/10000, 0.5600 +
> 30/10000, 0.5600 + 40/10000} /. {0.562 -> 0.5622, 0.563 -> 0.5637, 0.564
> -> 0.5641} {0.5622, 0.563, 0.5641} (* 0.563 gets replaced when typed in
> directly *) {0.562, 0.563, 0.564, 0.5630} /. {0.562 -> 0.5622, 0.563 ->
> 0.5637, 0.564 -> 0.5641} {0.5622, 0.5637, 0.5641, 0.5637}
>
>
> (*workaround*) replaceDigits[numList_List, replacementDigitsList_List] := ToExpression[ StringReplace[ ToString[PaddedForm[#, {5, 5}] & /@
> numList], Map[ToString[PaddedForm[#, {5, 5}]] &, replacementDigitsList,
> {2}] ] ] replaceDigits[data, {0.562 -> 0.5622, 0.563 -> 0.5637, 0.564
> -> 0.5641}] {0.5622, 0.5637, 0.5641}
>
Prev by Date:
**Re: Using ReplaceAll (/.) on numerical digits**
Next by Date:
**Re: Using ReplaceAll (/.) on numerical digits**
Previous by thread:
**Re: Using ReplaceAll (/.) on numerical digits**
Next by thread:
**Re: Using ReplaceAll (/.) on numerical digits**
| |