Saturday, April 5, 2008

print out the vector implementation

a=`locate stl_vector.h | head -n 1`; cat $a

Objective C doesn't have keyword/named arguments

This recently came up on Apple's Objective C list: Selectors vs named arguments. If Objective C really did have keyword arguments, then the following would be selector would be illegal: foo:foo:. But it's not. I know I've misspoken on this because I remember asking someone if there were any languages with nothing but keyword arguments, and then Smalltalk came falsely to mind. So, are there any languages with nothing but keyword arguments, ie, you must always use calls of the form foo(arg1="pizza")? This could of course seem a little irritating for functions with only one parameter. And now that I realize that Smalltalk is doing something else (duh!), the idea seems less appealing overall because I really like what Smalltalk does.

Saturday, March 29, 2008

scanf character classes -- oops

There was a serious bug in the code I posted for charToIntRange earlier (which I'll fix momentarily). I had thought that a character range "%[...]" in scanf acts like "%c" (with default width 1, no NUL added) but actually it acts like "%s". So, although &divider had the right type -- char* -- I was corrupting memory leading to an odd crash later. I guess the lesson for me is to read the documentation more thoroughly. (This is the first time I've used character classes in C. scanf suddenly seems much cooler than before now that I know of them.) This is also an error the compiler could catch though. If the argument corresponding to "%[...]" is a pointer to a char variable, this is always a sign of error. Maybe this case isn't common enough to warrant special attention though.

charClass2.c:
#include <stdio.h>
#include <string.h>

int main(int numArgs, char** args)
{
int i;
for (i = 0; i < numArgs; ++i) {
char x[3];
char y[1000];
if (sscanf(args[i], "%2[a]%999[a]", x, y) == 2) {
printf("%zu %zu\n", strlen(x), strlen(y));
}
else {
printf(":-(\n");
}
}
return 0;
}
$ gcc -Wall charClass2.c
$ ./a.out a aa aaa aaaa baaaa
:-(
:-(
:-(
2 1
2 2
:-(

("%zu" is not documented in the man page for printf on my system. I found it after getting warnings with earlier code about an incompatibility with size_t. It looks like it's a C99 extension. Discussion.)

//Actually... I didn't need a character class at all. Character literals match themselves. Of course! Ach. Lesson for me: Don't forget stuff like this.

//And it's not portable to assume char* index(const char *s, int c) is defined in string.h. I've switched to strchr, which I should've been using from the beginning.

generalized logit

This is what I feel like writing now:

y = a f(x)/(b + c f(x))
y b + y c f(x) = a f(x)
b y = (a - yc) f(x)
x = f^-1(b y / (a - y c))

Learn Haskell in 10 minutes... Finally!


stripHtml.hs:
stripHtml :: String -> String
stripHtml ('<':xs) = eatTag xs
stripHtml (x:xs) = x : stripHtml xs
stripHtml [] = []

eatTag :: String -> String
eatTag ('>':xs) = stripHtml xs
eatTag (x:xs) = eatTag xs
eatTag [] = []
$ ghci
___ ___ _
/ _ \ /\ /\/ __(_)
/ /_\// /_/ / / | | GHC Interactive, version 6.6, for Haskell 98.
/ /_\\/ __ / /___| | http://www.haskell.org/ghc/
\____/\/ /_/\____/|_| Type :? for help.

Loading package base ... linking ... done.
Prelude> :l stripHtml.hs
[1 of 1] Compiling Main ( stripHtml.hs, interpreted )
Ok, modules loaded: Main.
*Main> stripHtml "<b><blink>What's</blink></b><h1> a better</h1> way to d<tt>o this</tt>?"
"What's a better way to do this?"
This looks like fun.

Friday, March 28, 2008

Parse an int range parameter

#include <stdio.h>
#include <string.h>

/**
* If str is of the form "<m>:<n>",
* set *min = m
* and *max = n. Otherwise,
* if str if of the form "<n>",
* set *min = defaultMin and
* *max = n.
* Return the number of numbers
* successfully parsed (1 or 2 indicating success,
* 0 failure).
*/
int charToIntRange(const char* str,
int defaultMin,
int* min,
int* max)
{
if (strchr(str, ':')) {
if (sscanf(str, "%d:%d", min, max) == 2) {
return 2;
}
else {
return 0;
}
}
else {
*min = defaultMin;
return sscanf(str, "%d", max);
}
}

int main(int numArgs, char** args)
{
int i;
for (i = 1; i < numArgs; ++i) {
int m;
int n;
if (charToIntRange(args[i], -1666, &m, &n)) {
printf("%d:%d\n", m, n);
}
else {
printf("failed to parse <<%s>>\n", args[i]);
}
}

return 0;
}

$ gcc -Wall charToIntRange.c
$ ./a.out 1 155:7 -3:3 :1 1: 19:-1 19:1a t15:5
-1666:1
155:7
-3:3
failed to parse <<:1>>
failed to parse <<1:>>
19:-1
19:1
failed to parse <<t15:5>>


It should probably fail with an input of "19:1a", but I'll leave off worrying about that for now.

Is the format "%[:]" portable?

Wednesday, March 26, 2008

Rotate a matrix 90 degrees clockwise

R:

##Rotate a square matrix 90 degrees clockwise.
rot90 <- function(a) {
n <- dim(a)[1]
stopifnot(n==dim(a)[2])
t(a[n:1, ])
}

JavaScript:
Fill in a default value for every blank text field

Hello.

Matlab: Write numbers to a file:
f = fopen('test.txt', 'w');
fprintf(f, '%g\n', 1:50);
fclose(f);
(I'm sure there's a better way to do this.)

Wednesday, March 19, 2008

Marginal Ricians with correlated errors

First, what's a good way to generate errors with a desired correlation structure? Let's start with the following:
> d <- as.matrix(dist(1:4, diag=T, upper=T))
> s <- 0.3^d
> a <- chol(s)
> m <- matrix(nrow=10000,ncol=4)
> for (i in 1:10000) { x <- rnorm(4); m[i,] <- a %*% x}
> var(m)
[,1] [,2] [,3] [,4]
[1,] 1.09839578 0.30672920 0.1062927 0.03032918
[2,] 0.30672920 1.01055057 0.3031668 0.09055224
[3,] 0.10629268 0.30316682 1.0044863 0.27050059
[4,] 0.03032918 0.09055224 0.2705006 0.88942696
> s
1 2 3 4
1 1.000 0.30 0.09 0.027
2 0.300 1.00 0.30 0.090
3 0.090 0.30 1.00 0.300
4 0.027 0.09 0.30 1.000
Is it surprising to find the sample variance such a relatively poor approximation to the true variance even with 10000 observations? (I guess the answer is "no!")

Now, let's use this to see what happens to a mixture of marginally Rician distributions as the correlation gets cranked up.
##Produce elements that are marginally Rician distributed but for
##which the noise between elements is correlated with the
##structure cor(X_i, X_j) = cor(Y_i, Y_j) = rho^abs(i-j)
##but {X_i} independent of {Y_i}, i = 1:length(mu) and
##result[i] = sqrt(X_i^2 + Y_i^2).
##The value is a matrix of draws from the given distribution,
##each row a single draw so that the ith column corresponds
##to mu[i]
corRice <- function(mu, n, rho, sigma) {
k <- length(mu)
d <- as.matrix(dist(1:k, diag=TRUE, upper=TRUE))
r <- (rho ^ d)
a <- sigma * chol(r)
result <- matrix(nrow=n, ncol=k)
for (i in 1:n) {
x <- (a %*% rnorm(k)) + mu
y <- a %*% rnorm(k)
result[i, ] <- sqrt(x^2 + y^2)
}
result
}

> r0 <- corRice(rep(c(0, 50, 100), each=50), n=10000, rho=0, sigma=10)
> r1 <- corRice(rep(c(0, 50, 100), each=50), n=10000, rho=0.9, sigma=10)
> r2 <- corRice(rep(c(0, 50, 100), each=50), n=10000, rho=0.99, sigma=10)
> plot(quantile(r0, probs=(1:999)/1000), quantile(r1, probs=(1:999)/1000), xlab="quantiles with rho=0", ylab="quantiles with rho=0.9")
> plot(quantile(r0, probs=(1:999)/1000), quantile(r2, probs=(1:999)/1000), xlab="quantiles with rho=0", ylab="quantiles with rho=0.99")



Hmmmmmmmm.