Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I am trying to use a real function of a real variable written in C from Mathematica, my .tm file reads as follows:

:Begin:
:Function:       my_function
:Pattern:        MyFunction[ x_Real]
:Arguments:      { x }
:ArgumentTypes:  { Real }
:ReturnType:     Real
:End:

double my_function(double x) { /* snip */ return ret; }

I can compile with mcc, install the program from within Mathematica, and call my function as MyFunction[1.0], but it won't work if I call it with an integer argument, like MyFunction[1], as it is not automatically converted to a Real and then to a double.

How can I make my function work well also with integer arguments?

Also I have to apply some numerical Mathematica methods (like NMinimize, NIntegrate) and they fail when evaluating the function for integer values.

share|improve this question
1  
You can "overload" your function like MyFunction[x_Integer]:=MyFunction[N[x]]. –  Spawn1701D Jul 4 '13 at 16:19
    
That's what I need, I thought that N[integer] would remain an integer, but this is not the case. If you want to convert your comment into an answer I will accept it. Thank you! –  zakk Jul 4 '13 at 16:23
add comment

1 Answer

up vote 7 down vote accepted

When your C-function takes a double argument, then your template definition is not optimal, because the pattern x_Real forbids you to put anything else than a real number.

It's far more general if your function can take all arguments which can be converted into a real number. Two steps are required for this. First, you change your pattern to

:Pattern:        MyFunction[ x_?NumericQ]

which lets you even call your function with Pi or 1 or 1/E. Second thing, and this is probably not widely known: the :Arguments: section can evaluate code! Therefore, you can make the transition to a real number there:

:Arguments:      { N[x] }

Now you can call your MathLink function without a wrapper, because things like 1, Pi and 2/3 are converted automatically.

share|improve this answer
    
Thank you! Accepted! –  zakk Jul 4 '13 at 17:42
2  
+1, for the info on the :Arguments: section, alone. (The rest could be deserving of an upvote, also, but you'll have to work harder. :)) –  rcollyer Jul 5 '13 at 2:35
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.