Wednesday, August 26, 2009

Interpolation with SciPy

This didn't take long, thanks to SciPy.


from scipy.interpolate import interpolate as interp

xa = [i * 10 for i in range(10)]
ya = [200.0 + 1.5 * x for x in xa]

iobj = interp.interp1d(xa, ya)
i_xa = [i for i in range(90)]
i_ya = [iobj(x) for x in i_xa]

import pylab as pl
pl.plot(xa, ya, "o")
pl.plot(i_xa, i_ya, "-")
pl.ylim(0, 1000)
pl.show()

Friday, August 7, 2009

A portable way to pass a string to C as a macro


#define STRINGIZE_(x) #x
#define STRINGIZE(x) STRINGIZE_(x)


And call STRINGIZE(x) in subsequent code. This is useful when using the -D option in gcc -- without STRINGIZE(), extra double-quotes (\") must be added in order to pass strings as macros from the command line.

Sunday, March 1, 2009

Conditional expression in Python

It has bothered me for a long time that Python does not provide a conditional expression operator similar to the ?: operator used in C. But by some fortune, I ran across this Python snippet:

("False", "True")[var == True]

which does exactly the same as what you would write in C

var ? "True" : "False"

What a relief!

Tuesday, January 6, 2009

Erase/Replace

新的一年開始了。

我不要再害怕。

還要活的更從容。

這是這一年的新希望(似乎比往年成熟些?)。唸研究所,不論是知識上或是生活上都真的讓我學到很多很多;假如一直這樣下去,第一個目標也許可以達成一大部分。第二個目標似乎困難許多,但某種程度上也是建立在第一個目標上的吧。

繼續努力。

Sunday, January 4, 2009

Regex for matching floating point numbers

As simple as it sounds, there doesn't seem to be a standard regular expression for matching floating point numbers -- for some reason everyone seems to have their own preference: scientific notation or not, decimal points in the exponent or not... etc. Currently I'm settling with
([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]*\.?[0-9]+)?)

Actually for my purposes, I also need an optional unit, so I'm really using this
([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]*\.?[0-9]+)?)([a-zA-Z]*)

Friday, January 2, 2009

Preventing string truncation with snprintf()

One issue with using snprintf() (the buffer-overrun-preventing version of sprintf()) is that since the size of the char[] we're trying to "print" into is limited, truncation would occur if the string is longer than the char[] size. Yet after studying the manual carefully, I noticed that snprintf() actually returns the length of the resultant string, regardless of the size of the buffer. Below is a simple demonstration of how to prevent truncation with this feature and dynamical allocation of the character buffer.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
#define NC 10
#define ALONGSTRING "A long string of nonsense that would've been truncated."

size_t len;
char *string = calloc(NC, sizeof(*string));

len = snprintf(string, NC, ALONGSTRING);

printf("Truncated string: '%s'\n", string);

if(len >= NC) {
string = realloc(string, (len + 1) * sizeof(*string));
snprintf(string, len + 1, ALONGSTRING);
}

printf("Non-truncated string: '%s'\n", string);

free(string);

return 0;
}

Saturday, December 27, 2008

Embedding Python

I've finally written my first embedded Python program! The following is basically a "hello world" program that demonstrates the basics of writing a C program that interacts with Python. It starts the embedded Python environment, parses some input (which is stored in the __main__ namespace) and prints out that input directly from C.

#include <Python.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
PyObject *globals, *list, *name, *item, *mp;
Py_ssize_t i, n;

Py_Initialize();
PyRun_SimpleString("a = 'some text'; b = 123.456");
mp = PyImport_AddModule("__main__");
list = PyObject_Dir(mp);
n = PyList_Size(list);
printf("n=%d\n", n);
for(i = 0; i < n; i++) {
name = PyList_GetItem(list, i);
item = PyObject_GetAttr(mp, name);
if(PyString_Check(item))
printf("list[%d] (string): '%s' = '%s'\n", i, PyString_AsString(name), PyString_AsString(item));
else if(PyFloat_Check(item))
printf("list[%d] (float): '%s' = %g\n", i, PyString_AsString(name), PyFloat_AsDouble(item));
}
Py_Finalize();

return 0;
}


To compile this program, you'll need to do something like
gcc embed_python.c -I/usr/include/python2.5 -lpython2.5