### Re^2: log() and int() problem

 on Dec 25, 2012 at 21:03 UTC ( #1010287=note: print w/replies, xml ) Need Help??

in reply to Re: log() and int() problem
in thread log() and int() problem

Thank you very much. I solved my issue with adding and subtracting 1 from the returned value.
I think that perl should do this internally.
```my \$l = log(125) / log(5);

\$l += 1;
\$l -= 1;

print \$l == int(\$l);

Thank you all for the great answers.

Replies are listed 'Best First'.
Re^3: log() and int() problem
by eyepopslikeamosquito (Chancellor) on Dec 25, 2012 at 22:40 UTC

I solved my issue with adding and subtracting 1 from the returned value
Sorry, but that's a terrible "solution". Your example floating point inaccuracy happens to be slightly greater than three. Since the int function truncates, consider what happens if the inaccuracy happens to be slightly less than three. Though a crude fix would be to add 0.5 (i.e. int(\$l+0.5) instead of int(\$l)), the perl documentation advises against using int for rounding and suggests sprintf and the POSIX floor and ceil functions as sounder alternatives.

Still don't understand why you don't go with moritz's solution.

> Though a crude fix would be to add 0.5 (i.e. int(\$l+0.5)

I think you rather meant something like \$ll=int(\$l+5e-15) =)

(15 digits accuracy is just a guess)

Cheers Rolf

Re^3: log() and int() problem
by LanX (Chancellor) on Dec 25, 2012 at 21:11 UTC
> I solved my issue

you're very optimistic.

I delved into Devel::Peek and I'm still not sure which type casting or crossed thresholds produced different results for 2 and 3.

Anyway you're voyaging dangerous grounds, don't be surprised if your Float to Int conversions breaks again.

Better rely on on already shown pure integer arithmetic for your integer (sic) tests. (rule of thumb!)

Cheers Rolf

PS:

```lanx@nc10-ubuntu:~\$ perl -MDevel::Peek -e'\$|=1;\$e=2;\$x=log(5**\$e)/log(
+5); Dump \$x; print ("\n", (\$x==\$e) ? "" : "not " ,"equal\n\n");  Dump
+ \$x;'

SV = NV(0x9c86840) at 0x9c70f68
REFCNT = 1
FLAGS = (NOK,pNOK)
NV = 2

equal

SV = PVNV(0x9c50a60) at 0x9c70f68
REFCNT = 1
FLAGS = (IOK,NOK,pIOK,pNOK)
IV = 2
NV = 2
PV = 0

lanx@nc10-ubuntu:~\$ perl -MDevel::Peek -e'\$|=1;\$e=3;\$x=log(5**\$e)/log(
+5); Dump \$x; print ("\n", (\$x==\$e) ? "" : "not " ,"equal\n\n");  Dump
+ \$x;'

SV = NV(0x8fde840) at 0x8fc8f68
REFCNT = 1
FLAGS = (NOK,pNOK)
NV = 3

not equal

SV = PVNV(0x8fa8a60) at 0x8fc8f68
REFCNT = 1
FLAGS = (NOK,pIOK,pNOK)
IV = 3
NV = 3
PV = 0

UPDATE: improved code

Create A New User
Node Status?
node history
Node Type: note [id://1010287]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2017-08-22 20:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Who is your favorite scientist and why?

Results (340 votes). Check out past polls.

Notices?