Message Boards Message Boards

How can I truncate the fractional part of a number in base 2?

Posted 12 years ago
If I have a fractional value, how can I truncate (not round) that to a certain number of bits, like 8?

For example, for Pi 3.141569265359... the fractional part is 0.141569265359...
NumberForm[BaseForm[FractionalPart[N[Pi]],2],8]

0.00100100001111110110101010001

But this is giving me 8 decimal digits of PI in base 2. What I want is 8 binary digits in base 2.
POSTED BY: Hairy Thoughter
Try to use RealDigits:
RealDigits[fp, 2, 8, -1][[1]]
this gives a list of numbers, you could use ToString and StringJoin to make a complete string. 

here is a working example:
GiveMeRealDigitsBehindCommaString[number_,base_,length_]:="0."<>StringJoin[ToString/@RealDigits[FractionalPart[number],base,length,-1][[1]]]
GiveMeRealDigitsBehindCommaString[N[\[Pi]],2,8]
this will return:
"0.00100100" (as a string)
POSTED BY: Sander Huisman
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract