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 would like to input a pure function into a custom written package, but am running into a variety of errors. The package I have created is as follows:

BeginPackage["functions`"]

CosCoeff::usage="CosCoeff[m] returns cheb coeffs of order m of Cosine[2 Pi t]";

Begin["`Private`"]

ClearAll["Global`*"]

CosCoeff[m0_]:=
Module[{m=m0},
f[t]=Cos[2 Pi t];
Tn[t] = ChebyshevT[j, 2*t - 1]; 
wt[t] = 1/Sqrt[t - t^2]; 

p=Table[Chop[NIntegrate[f[t]*Tn[t]*wt[t], {t, 0, 1}]/(N[Pi]/2.0)], {j, 0, m-1}];
p[[1]]=p[[1]]/2;
p
]

End[]
EndPackage[]

This package as stated creates a table containing "m" shifted-Chebyshev coefficients for the function Cos[2 Pi t]. How can I input any function, say Sin[2 Pi t], instead of writing a different module for every function I need to use?

share|improve this question

1 Answer 1

up vote 5 down vote accepted

You can pass a function (or for that matter, anything!) as an argument to another function and you'll need to modify your code accordingly. See this example:

ChebyCoeff[func_, m0_] := Module[{m = m0},
    f[t] = func[2 Pi t];
    Tn[t] = ChebyshevT[j, 2*t - 1];
    wt[t] = 1/Sqrt[t - t^2];
    p = Table[Chop[NIntegrate[f[t]*Tn[t]*wt[t], {t, 0, 1}]/(N[Pi]/2.0)], {j, 0, m - 1}];
    p[[1]] = p[[1]]/2;
    p
]

Now ChebyCoeff[Cos, 3] will give the same result as your CosCoeff[3].

share|improve this answer
    
Excellent! That's a step in the right direction. Now, is it possible to pass an entire function along with its argument/s? Say I want to evaluate 'f[t]=Sin[t]', 'Cos[Pi t]Sin[0.5 t]', 't+t^3', etc? –  gKirkland Mar 31 at 16:38
    
@gKirkland Sure. Change the line to f[t] = func[t]; and then pass a pure function such as Cos[Pi #]Sin[0.5 #]& or # + #^3& to your function. –  rm -rf Mar 31 at 17:02

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.