Episode #125 of the Stack Overflow podcast is here. We talk Tilde Club and mechanical keyboards. Listen now

Hot answers tagged

22

We can take advantage of the fact that IntegerDigits is very fast when the base is large. But not too large: no bigger than $2^{63}-1$ on a 64-bit system or $2^{31}-1$ on a 32-bit one, because Mathematica's machine integers are signed. Additionally, non-power-of-two bases require more work to get the result than just partitioning a bit-string, and are ...


21

matOP = {{0, 1, 0, 0, 1, 0, 1, 0}, {0, 1, 0, 0, 1, 0, 1, 0}, {0, 0, 1, 0, 1, 0, 1, 0}, {0, 0, 0, 1, 0, 0, 1, 0}, {0, 0, 0, 0, 1, 1, 0, 0}, {0, 0, 0, 0, 1, 0, 0, 0}}; $\left( \begin{array}{cccccccc} 0 & 1 & 0 & 0 & 1 & 0 & 1 & 0 \\ 0 & 1 & 0 & 0 & 1 & 0 & 1 & 0 \\ 0 & 0 & 1 & ...


21

The file appears to be a Unified Summary File from the Schlumberger Eclipse Reservoir Simulator. This file format uses Compaq Visual Fortran variable length record encoding. Mathematica does not offer any built-in functionality to read this file format, so we will have to parse it ourselves. We start by defining a convenience function to read big-endian ...


19

Leonid has shown how to get a big improvement in speed with Java and has mentioned that by using a library function written e.g. in C you could probably get further improvement as you can then avoid additional copies/data transfer. I just wanted to add an all Mathematica solution as it probably indicates how similar problems can be tackled where for ...


16

I was able to get 50x speedup w.r.t. your fastest code by using highly optimized Java buffered read functionality. The idea The idea is quite simple: use buffered read to reduce the IO overhead, and use Java to reduce the symbolic Mathematica overhead. Implementation You will have to run the Java reloader. Then, you call JCompileLoad@" import java....


16

There is in fact an easy test to determine if an integer is a power of $2$, thanks to bit twiddling: hadamardMatrix[1] := {{1}} hadamardMatrix[2] := {{1, 1}, {1, -1}} hadamardMatrix[n_Integer /; Positive[n] && BitAnd[n, n - 1] == 0] := KroneckerProduct[hadamardMatrix[2], hadamardMatrix[n/2]]


15

This should be reasonably efficient. BitRotateRight[n_Integer, m_Integer] /; n > 0 && m >= 0 := BitShiftRight[n, m] + BitShiftLeft[Mod[n, 2^m], (BitLength[n] - m)] Will need to modify for left rotations if you want to support negative m. I added the restriction that n be positive. Not exactly sure what should be the behavior for negative n. ...


15

Solution It appears this bug is the result of attempted parallelism gone wrong. I believe it is corrected in all cases by setting this System Option: SetSystemOptions[ "ParallelOptions" -> {"MachineFunctionParallelThreshold2" -> Infinity} ] This appears to be an out and out bug and I tagged the question accordingly. Original observations: Compact ...


14

mtrx = {{0, 1, 0, 0, 1, 0, 1, 0}, {0, 1, 0, 0, 1, 0, 1, 0}, {0, 0, 1, 0, 1, 0, 1, 0}, {0, 0, 0, 1, 0, 0, 1, 0}, {0, 0, 0, 0, 1, 1, 0, 0}, {0, 0, 0, 0, 1, 0, 0, 0}}; Once we re-number the elements of mtrx using a function like renumber = Module[{i = 1}, # /. 1 :> i++] &; (* thanks: Mr.W *) mtrx2 =renumber@mtrx ...


14

ClearAll[countZ] countZ = 1 ## & @@ Dimensions @ # - Total[#, 2] &; countZ@binarym 17 Timings: SeedRandom[1] binm = RandomInteger[{0, 1}, {10000, 10000}]; countZ @ binm // AbsoluteTiming {0.23863, 49996224} Wavelets`CountZeros@binm // AbsoluteTiming {0.520381, 49996224} (Length @ # - Total @ #) & @ Flatten @ binm // AbsoluteTiming (*...


13

I imported the data this way: data = Import["ftp://software.seg.org/pub/datasets/2D/Hess_VTI/timodel_vp.segy.gz", "Binary"]; nByteFile = Length@data nByteTrace = (nByteFile - 3600)/3617 nTraceSample = (nByteTrace - 240)/4 22573680 6240 1500 You have to convert bytes to IBM 32-bit floating-point yourself. This takes a list of bytes, ...


13

An interesting question which I've never specifically considered before. Some observations: Log[8]/Log[2] // FullSimplify Log2[8] Log[2, 8] 3 3 3 And @@ IntegerQ /@ Log2[2^Range[50000]] And @@ Table[IntegerQ@Log2[2^RandomInteger[5*^8]], {500}] True True Mathematica documentation explicitly states: Log2 gives exact integer or rational number ...


12

To decipher the header structure is not really a question that we should solve here, but I can show you how to read this file in a structured way. In order to assist you in deciphering and to demonstrate the necessary tools I have build the below file and data browser. Everything you need can be found in this short program. (*Use this out-commented part if ...


12

How about this? nextpow2[a_] := Ceiling @ Log[2, Abs @ a]; or nextpow2[a_] := Ceiling[RealExponent[a, 2]] The same thing in a different style: f1 = Ceiling @* Log2 @* Abs; (* v10 syntax *) Or: f2 = ⌈Log2 @ Abs @ #⌉ &; A plot: Plot[f2[x], {x, -10, 10}, Filling -> 0]


12

You can input numbers in any base up to 36 using the notation base^^digits. Digits over 9 are represented using a, b, c, ... You can print numbers in any base up to 36 using BaseForm. Thus, In[1]:= a=2^^0.10101 Out[1]= 0.65625 In[2]:= BaseForm[a^2,2] Out[2]//BaseForm= Subscript[0.0110111001, 2] Note that the internal representation of numbers doesn't ...


10

There isn't really such a thing as binary arithmetic (at least in Mathematica). Numbers can be represented in any base, and this user-visible representation is completely independent from how arithmetic is done. Try this: BaseForm[(2^^1010101011)*(2^^1111101110), 2] Things to look up: BaseForm Digits in numbers


10

You could try Tuples: Tuples[{0, 1}, 4] (* {{0,0,0,0},{0,0,0,1},{0,0,1,0},{0,0,1,1}, {0,1,0,0},{0,1,0,1},{0,1,1,0},{0,1,1,1}, {1,0,0,0},{1,0,0,1},{1,0,1,0},{1,0,1,1}, {1,1,0,0},{1,1,0,1},{1,1,1,0},{1,1,1,1}} *)


10

bin = 1011011; words = (bin // IntegerDigits) /. {1 -> "one", 0 -> "zero"}; (str = StringJoin[Riffle[words, " "]]) // InputForm (* "one zero one one zero one one" *) Speak[str]


10

Updated to include suggestions from comments My original idea, using BitAnd, switching $0\leftrightarrow1$, and multiplying. This idea uses 3 vectorized binary operations: erode1[list_] := Times[ list, Subtract[ 1, BitAnd[list, PadRight[list, Length@list, 0, 1]] ] ] Here is @Shadowray's improvement, which uses 2 vectorized ...


10

twosComplement[x_, n_] := UnitBox@IntegerDigits[x, 2, n] twosComplement[35, 8] {1, 1, 0, 1, 1, 1, 0, 1}


9

LengthWhile[#, Positive] & /@ binarym {3, 4, 2, 4, 6} Or binarym /. {x : Longest[1 ..], __} :> Length[{x}]


9

I will turn Kuba's comment into an answer. The EncryptedObject you create using Encrypt contains the encrypted data and the initialization vector of the encryption method as a ByteArray. These can be turned into an array of digits using Normal and IntegerDigits. key = GenerateSymmetricKey[]; message = "Hello world"; eobj = Encrypt[key, message]; bin = eobj[...


9

I don't think there is a built-in function to generate the two's complement representation. Easy to implement though. twosComplement[x_, n_] := IntegerDigits[2^x - n, 2, n] twosComplement[35, 8] (* {1, 1, 0, 1, 1, 1, 0, 1} *)


9

The problem is the following: Mod[Plus @@ IntegerDigits[n, 2], 2] Mod[2 + n, 2] This happens because IntegerDigits stays unevaluated for non integer inputs: IntegerDigits[n, 2] IntegerDigits[n, 2] Note that this sum remains unevaluated: Sum[ThueMorse[n]/(n + 1)^s, {n, 0, Infinity}] Sum[ThueMorse[n]/(n + 1)^s, {n, 0, Infinity}] Ideally Alpha should ...


8

The following function is based on the Ramp and Differences functions, as suggested in a comment by @garej . Its speed and low memory are surprising. rampDiff[list_] := Ramp@Prepend[Differences[list], First[list]] It was tested against the following functions from previous answers and comments: ClearAll["Global`*"] erode1[list_] := Times[list, ...


8

Update: ff works as is in version 9. For versions 10+, as commented by @Mr.Wizard, it needs to be modified to prevent the index i from exceeding the length of the input list: ffX[m_] := With[{n = Length@First@m}, Module[{i = 1}, While[i <= n && Positive[#[[i]]], ++i]; i - 1] & /@ m] (* thanks: @Mr.Wizard *) Original answer: ClearAll[f1] ...


7

The short answer is, you can't. The only function that can really consume these objects is not exposed at the language level but only in the kernel's own C code. To be honest, am not sure why it is even in the system. My best guess is that there a few obscure case where it might be generated by internal code. Given that we don't even document it anymore (...


7

Using old-school GraphPlot: Edit: the comments that broke the code have been removed. input = {{0,1,0,0,1,0,1,0}, {0,1,0,0,1,0,1,0}, {0,0,1,0,1,0,1,0}, {0,0,0,1,0,0,1,0}, {0,0,0,0,1,1,0,0}, {0,0,0,0,1,0,0,0}}; new = Module[{i = 1}, input /. 1 :> i++]; Developer`PartitionMap[Union @@ # &, %, {2, 2}, 1]; Union @@ DeleteCases[%, 0, {-1}]; ...


7

If I am not mistaken the 212 format is storing two signals and each 3-byte group provides a 12-bit reading of that pair. Importing with Byte isn't too bad for this set: data = Import["http://physionet.org/physiobank/database/mitdb/100.dat", "Byte"] ~ Partition ~ 3 Then two helpers to parse it: twosComplement[a_, n_] := If[a < 2^(n - 1), a, a - 2^n] ...


Only top voted, non community-wiki answers of a minimum length are eligible