By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,007 Members | 1,020 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,007 IT Pros & Developers. It's quick & easy.

Data conversion,a simple but strange problem,please help!

P: n/a
Hi,

We all know that the return value of Math.Log(8,2) is 3,but how about
(int)Math.Log(8,2)? On my machine,the return value of (int)Math.Log(8,2) is
strange enough! it's not 3 but 2 ! I've tested other values such as
(int)Math.Log(16,2),(int)Math.Log(4,2),(int)Math.L og(32,2)...et, they all
return the same value as their counterpart Math.Log() methods,only
(int)Math.Log(8,2) is incorrect,is this a .net bug ? I've also tested
Math.Floor(Math.Log(8,2)),its return value is same as (int)Math.Log(8,2),but
Math.Ceiling(Math.Log(8,2)) and int.Parse(Math.Log(8,2).ToString()) returns
the correct value of 3! Dose anyone know what caused this strange behavior?
thanks in advance!
Feb 25 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a

"Webdiyer" <we******@hotmail.com> wrote in message
news:OJ*************@TK2MSFTNGP11.phx.gbl...
Hi,

We all know that the return value of Math.Log(8,2) is 3,


No it's not. Math.Log(8,2) is a double precision floating point value
guaranteed only to be pretty darn close to 3.

It's like the add for the new Delta shaver:
It's not just close, it's Eplsilon-close!

In particular (3 - double.Epsilon) < Math.Log(8,2) < (3 + double.Epsilon).

When you convert it to an integral type, you should explicitly apply
whatever rounding behavior you want. Or else perform your arithmetic on
integers only.

David
Feb 25 '06 #2

P: n/a
Thank you for your quick reply,I've solved this problem by first converting
Math.Log(8,2) to decimal value and then converting this value to int,this
way the result is correct.
"David Browne" <davidbaxterbrowne no potted me**@hotmail.com> wrote in
message news:OH****************@TK2MSFTNGP12.phx.gbl...

"Webdiyer" <we******@hotmail.com> wrote in message
news:OJ*************@TK2MSFTNGP11.phx.gbl...
Hi,

We all know that the return value of Math.Log(8,2) is 3,


No it's not. Math.Log(8,2) is a double precision floating point value
guaranteed only to be pretty darn close to 3.

It's like the add for the new Delta shaver:
It's not just close, it's Eplsilon-close!

In particular (3 - double.Epsilon) < Math.Log(8,2) < (3 +
double.Epsilon).

When you convert it to an integral type, you should explicitly apply
whatever rounding behavior you want. Or else perform your arithmetic on
integers only.

David

Mar 1 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.