boost::shared_ptr / QuantLib / stochastic process / path generation - shared-ptr

Happy Holidays, everyone !
I'm trying to generate paths of a square root process using the QuantLib/Boost C++ libraries and have encountered what I believe to be an annoying little problem with a fast and simple solution! I'm pretty new to programming so please don't be too harsh on me :)
Here's what I know:
1. The constructor looks like this:
SquareRootProcess( Real b, Real a, Volatility sigma, Real x0 = 0.0,
const boost::shared_ptr<discretization>& d =
boost::shared_ptr<discretization>(new EulerDiscretization))
The crucial function to be used when simulating a stochastic process with QuantLib is
evolve(t,x,dt,dw).
Here's what my code looks like:
#include "stdafx.h"
#include <ql/quantlib.hpp>
#include <ql/stochasticprocess.hpp>
#include <ql/processes/squarerootprocess.hpp>
#include <ql/Processes/eulerdiscretization.hpp>
using namespace QuantLib;
void SquareRootProcessSimulation()
{
Real miu0=0.0;
Real miu;
Real b=0.3;
Real a=5.5;
Volatility sigma=2.02;
BigInteger seed=12324;
MersenneTwisterUniformRng unifMt(seed);
BoxMullerGaussianRng<MersenneTwisterUniformRng> bmGauss(unifMt);
const boost::shared_ptr<StochasticProcess1D::discretization> &d =
boost::shared_ptr<StochasticProcess1D::discretization>(
EndEulerDiscretization);
boost::shared_ptr<SquareRootProcess> squareRootProcess(new
SquareRootProcess(b, a, sigma, miu0, d&));
Time dt=0.1,t=0.0;
Real dw;
Size numVals=10;
for (Size j=1;j<=numVals;++j)
{
dw=bmGauss.next().value;
miu=squareRootProcess->evolve(t,miu0,dt,dw);
std::cout << "Time: " << t+dt << ", miu_t: " << miu << std::endl;
t+=dt;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
SquareRootProcessSimulation();
std::cin.get();
return 0;
}
`
I get no errors when compiling/running the code, but what comes out is a constant value, i.e. something is obviously wrong. I think the problem is in the way I've defined the stochastic process, I cannot quite figure out how the interpret the last part of the constructor with the boost::shared_ptr.
I'm happy to hear any suggestions and hints and thanks for taking the time to read my question!
best regards :)

I'm not quite sure if this will solve the problem, but at least I want to try to help:
First of all let's have a look the constructor
of SquareRootProcess:
SquareRootProcess( Real b,
Real a,
Volatility sigma,
Real x0 = 0.0,
const boost::shared_ptr<discretization>& d = boost::shared_ptr<discretization>(new EulerDiscretization))
As you can see the last two parameters have default values. This means you can call the function like this
SquareRoot(b,a,sigma);
This would mean that the function is called with the values of b, a and sigma. x0 and d ( the last two parameters ) would get their default values as written in the constructor. In this case that would be 0.0 for x0 and a new shared pointer object of the type discretization.
But since you want the value from the last paramter the default value is not the right choice for you.
As far as I can tell the function SquareRootProcess will calculate some stuff and then store the data at the pointers address. Here we come to the second part of the Constructor, the &.
The & in the parameter list means that you pass the function a reference to a shared pointer. This means if you call the function your pointer will ( most likely ) be changed and point to the desired value. If the function has a call by reference you actually don't need to add any signs in the function call. Just to make things clear, the same process with some integers:
void add(int a,int b,int& sum)
{
sum = a + b;
}
int main()
{
int sum;
add(5,12,sum);
// Now sum has the value 17
return 0;
}
So long story short : If a function expects a reference to an object you just pass the object itself in the function call.
So now back to your case:
You just need to create an shared pointer with the type discretization and then pass it on in the function call.
const boost::shared_ptr<StochasticProcess1D::discretization> d(new StochasticProcess1D::discretizitation(/*Whatever constructor is needed for this type*/));
boost::shared_ptr<SquareRootProcess> squareRootProcess(new SquareRootProcess(b, a, sigma, miu0, d));
This should actually do the deal. Just let me know if it worked or if you have any further questions.
Best Regards

As already pointed out, you don't need to pass the discretization object if you don't want to customize it, so
boost::shared_ptr<SquareRootProcess> squareRootProcess(new
SquareRootProcess(b, a, sigma, miu0));
will do for you. The problem I'm seeing is with the repeated calls to evolve; you wrote
miu=squareRootProcess->evolve(t,miu0,dt,dw);
but that will cause each step to always start from miu0. The idea here is that you start from t=0 and x=miu0 and evolve() gives you the new miu at t=0.1. Then you start from t=0.1 and x=miu (not miu0) and generate another step. So you'll have to write something like:
miu = miu0;
for (Size j=1;j<=numVals;++j)
{
...
miu=squareRootProcess->evolve(t,miu,dt,dw); // not miu0
...
}
to get the desired behavior.
As for documentation, you might want to take a look at chapter 6 of Implementing QuantLib, which describes the Monte Carlo framework. It will also get you started with path generators; you can use those to generate paths without having to drive the process yourself.
Oh, by the way: is there any particular reason you're using the docs at sourcearchive.com, instead of the "official" ones on quantlib.org? Is there any way you think we should improve them?

Related

The definition of a function in C

I have an assignment question which ask me about the definition of a function. I'm not quite sure how it want me to answer. The question is below:
Write the definition of a function multiplier(), which has two real parameters n and m, and which returns value of n multiplied by m
Write the definition of a function multiplier(), which has two real parameters n and m, and which returns value of n multiplied by m
Lets try to unwrap this, there are no real-type in C so Real is the code word for float or double. Function is the name of a subroutine.
The wording of the question is vague definition could ask for the optional prototype declaration(the definition of functions which is usually stored in the header files) which is
float multiplier(float,float);
or the function could be defined and implemented at the same time
float multiplier(float n, float m){
return (n*m);
}
Your question is,
Write the definition of a function multiplier(), which has two real parameters n and m, and which returns value of n multiplied by m
A function is a certain way to write a code, that way you can call it in the main, or wherever, and it performs any tasks assign to it. In your case, for your multiplier, it will perform the function of multiplication. Therefore, it would make sense to use two integers in order to perform this task.
To start, since we will be returning an int, we will call it as that. We set it up like this,
type name (*parameters)
{
}
in your case,
int multiplier(Parameters go here)
For the code:
int multiplier(int m, int n)
{
return m*n;
}
then when we call it in the main, we would pass two numbers for the multiplier and it will return it as a product.
int main()
{
multipler(2, 4); // prints 8
}
I hope this helps, I tried to explain it very basic.

Usefulness of return value not depending on all (exclusively call-by-value) parameters

I have one question:
int swapnum( int x, int y )
{
int tempnum ;
tempnum = x ;
x = y ;
y = tempnum ;
return tempnum;
}
int swapnum(int, int);
int main( )
{
int x = 35, y = 45 ;
printf("Before swapping: %d, %d", x, y);
swapnum(x, y);
printf("\nAfter swapping: %d, %d", x, y);
return 0;
}
I have found this example in internet which demonstrates how call by value works. I understand everything except one thing. For what do we need call by value if we do not get changed result in main? I understood idea of call by reference; we will receive changed result but for what do we need call by value if result is changed only locally (in upper part of this code) and main stays unchanged (printf("\nAfter swapping: %d, %d", x, y);)? And if you write your example too to demonstrate it would be great.
There are even functions which do not return anything.
They have a prototype like
void useTwoNums(int, int);
They illustrate even better than your example that it is not necessary to return anything, even less something which somehow uses the two input parameters and/or depends on them.
The concept which you seem to be missing is the difference between "functions" in mathematical context and "functions" in programming. In programming a function might well do something without returning something. One example is a function which just nicely prints the input values, compare printf(),
http://en.cppreference.com/w/c/io/fprintf
Its return value can be handled inside the return-value-free function to illustrate.
The extreme case would be a function with neither parameters nor return value:
void DoSomethingInFreespace(void);. Functions like that can achieve the data to process e.g. via other input channels. Or they are simply refactored pieces of code, e.g. for reuse, which have a sufficiently rich context, e.g. global or file local variables.
To make the answer more complete, I will integrate some points from comments (including the one by OP, which focuses on return values):
With call-by-value functions are more close to mathematical functions, and are then much more easily composed. (Jean-Baptiste Yunès).
and
it allows you to send values without worrying that some function will change them. It's very convenient. (njzk2)
Both (and other, too) stress that a mathematical function does not alter the parameters; this is something of a "promise" which programmers appreciate.
Turning it around:
when using call by value if you want that [a value in the context outside of the function, e.g.] main be changed we must return the result (OP)
Different angle:
when using call by reference, we don't need to return; it [the parameter] itself changes [outside of the context of the called function and can be used as a] result (OP)
I have found this example in internet which demonstrates how works call by value. I understand everything except one thing: for what do we need call by value?
You don't need call-by-value. But call-by-value is how C works, and most programming languages actually, so you would do well to learn it.
I understood idea of call by reference, we will receive changed result but for what do we need call by value if result is changed only locally
Call-by-value is used in most programming languages because it makes it easier to think about the code. When you see doStuff(x, y); you know that x and y won't change. They can only change if you write doStuff(&x, &y); or x = doStuff(y); or something like that. You don't need go and look up the DoStuff Manual to find out whether doStuff is supposed to change them.
and if you write your example too to demonstrate it would be great.
There's really nothing to demonstrate; the point of call-by-value is that nothing happens. Do you want a demonstration of nothing happening?
The return value is useful when you have formulas.
If you want to calculate the hypotenus from the cathetus and you pass the value of the latters, you do not want theit value modified.

passing a constant through a function in C

I have some C function which, among other things, does a modulo operation. So it looks something like
const int M = 641;
void func( ...parameters..) {
int x;
... some operations ...
x %= M;
... some more operations ...
}
Now, what is crucial for me is that the number M here is a constant. If I would not tell the compiler that M is a constant, then I would get much slower performance.
Currently, I am very happy with my function func( .. ) , and I want would like to extend it, so it can work on different moduli. But again, it is crucial here that these moduli are fixed. So I would like to be able to do something like
const int arrayM[] = {641, 31, 75, 81, 123};
and then have for each index in the array of constants array_M[i] a version of the function func, say func_i, which is a copy of the function func, but where array_M[i] replaces the role of M.
In practice, my array of constants arrayM[] will consist of around 600 explicit prime numbers, which I will choose in a particular way so that x % array_M[i] compiles to a very fast modulus function (for instance Mersenne primes).
My question is: How do I do this in C without making 600 copies of my function func, and changing the variable M in the code each time ?
Finally, I would like to ask the same question again for CUDA code. So if I would have a cuda-kernel, where at some point in the code a modulus M operation is carried out, and I want to have different copies of the same kernel (one for each index of array_M).
You may use a define like:
#define F(i,n) void func_##i() { printf("%d\n",n); }
#include <stdio.h>
F(1,641)
F(2,31)
...
int main() {
func_1();
func_2();
}
It is possible to obtain the same effect from a list of constant but it is much much more tricky. See recursive macro.
Most compilers will do constant propagation. You need to turn up the optimisation level high. The only way to be sure however is to examine the assembly code, or to explicitly write the code out with the constants folded in, which is ugly and hard to maintain. C++ allows you to specify a scalar as a template.

Designing Around a Large Number of Discrete Functions in C

Greetings and salutations,
I am looking for information regrading design patterns for working with a large number of functions in C99.
Background:
I am working on a complete G-Code interpreter for my pet project, a desktop CNC mill. Currently, commands are sent over a serial interface to an AVR microcontroller. These commands are then parsed and executed to make the milling head move. a typical example of a line might look like
N01 F5.0 G90 M48 G1 X1 Y2 Z3
where G90, M48, and G1 are "action" codes and F5.0, X1, Y2, Z3 are parameters (N01 is the optional line number and is ignored). Currently the parsing is coming along swimmingly, but now it is time to make the machine actually move.
For each of the G and M codes, a specific action needs to be taken. This ranges from controlled motion to coolant activation/deactivation, to performing canned cycles. To this end, my current design features a function that uses a switch to select the proper function and return a pointer to that function which can then be used to call the individual code's function at the proper time.
Questions:
1) Is there a better way to resolve an arbitrary code to its respective function than a switch statement? Note that this is being implemented on a microcontroller and memory is EXTREMELY tight (2K total). I have considered a lookup table but, unfortunately, the code distribution is sparse leading to a lot of wasted space. There are ~100 distinct codes and sub-codes.
2) How does one go about function pointers in C when the names (and possibly signatures) may change? If the function signatures are different, is this even possible?
3) Assuming the functions have the same signature (which is where I am leaning), is there a way to typedef a generic type of that signature to be passed around and called from?
My apologies for the scattered questioning. Thank you in advance for your assistance.
1) Perfect hashing may be used to map the keywords to token numbers (opcodes) , which can be used to index a table of function pointers. The number of required arguments can also be put in this table.
2) You don's want overloaded / heterogeneous functions. Optional arguments might be possible.
3) your only choice is to use varargs, IMHO
I'm not an expert on embedded systems, but I have experience with VLSI. So sorry if I'm stating the obvious.
The function-pointer approach is probably the best way. But you'll need to either:
Arrange all your action codes to be consecutive in address.
Implement an action code decoder similar to an opcode decoder in a normal processor.
The first option is probably the better way (simple and small memory footprint). But if you can't control your action codes, you'll need to implement a decoder via another lookup table.
I'm not entirely sure on what you mean by "function signature". Function pointers should just be a number - which the compiler resolves.
EDIT:
Either way, I think two lookup tables (1 for function pointers, and one for decoder) is still going to be much smaller than a large switch statement. For varying parameters, use "dummy" parameters to make them all consistent. I'm not sure what the consequences of force casting everything to void-pointers to structs will be on an embedded processor.
EDIT 2:
Actually, a decoder can't be implementated with just a lookup table if the opcode space is too large. My mistake there. So 1 is really the only viable option.
Is there a better way ... than a switch statement?
Make a list of all valid action codes (a constant in program memory, so it doesn't use any of your scarce RAM), and sequentially compare each one with the received code. Perhaps reserve index "0" to mean "unknown action code".
For example:
// Warning: untested code.
typedef int (*ActionFunctionPointer)( int, int, char * );
struct parse_item{
const char action_letter;
const int action_number; // you might be able to get away with a single byte here, if none of your actions are above 255.
// alas, http://reprap.org/wiki/G-code mentions a "M501" code.
const ActionFunctionPointer action_function_pointer;
};
int m0_handler( int speed, int extrude_rate, char * message ){ // M0: Stop
speed_x = 0; speed_y = 0; speed_z = 0; speed_e = 0;
}
int g4_handler ( int dwell_time, int extrude_rate, char * message ){ // G4: Dwell
delay(dwell_time);
}
const struct parse_item parse_table[] = {
{ '\0', 0, unrecognized_action } // special error-handler
{ 'M', 0, m0_handler }, // M0: Stop
// ...
{ 'G', 4, g4_handler }, // G4: Dwell
{ '\0', 0, unrecognized_action } // special error-handler
}
ActionFunctionPointer get_action_function_pointer( char * buffer ){
char letter = get_letter( buffer );
int action_number = get_number( buffer );
int index = 0;
ActionFunctionPointer f = 0;
do{
index++;
if( (letter == parse_table[index].action_letter ) and
(action_number == parse_table[index].action_number) ){
f = parse_table[index].action_function_pointer;
};
if('\0' == parse_table[index].action_letter ){
index = 0;
f = unrecognized_action;
};
}while(0 == f);
return f;
}
How does one go about function pointers in C when the names (and
possibly signatures) may change? If the function signatures are
different, is this even possible?
It's possible to create a function pointer in C that (at different times) points to functions with more or less parameters (different signatures) using varargs.
Alternatively, you can force all the functions that might possibly be pointed to by that function pointer to all have exactly the same parameters and return value (the same signature) by adding "dummy" parameters to the functions that require fewer parameters than the others.
In my experience, the "dummy parameters" approach seems to be easier to understand and use less memory than the varargs approach.
Is there a way to typedef a generic type of that signature
to be passed around and called from?
Yes.
Pretty much all the code I've ever seen that uses function pointers
also creates a typedef to refer to that particular type of function.
(Except, of course, for Obfuscated contest entries).
See the above example and Wikibooks: C programming: pointers to functions for details.
p.s.:
Is there some reason you are re-inventing the wheel?
Could maybe perhaps one of the following pre-existing G-code interpreters for the AVR work for you, perhaps with a little tweaking?
FiveD,
Sprinter,
Marlin,
Teacup Firmware,
sjfw,
Makerbot,
or
Grbl?
(See http://reprap.org/wiki/Comparison_of_RepRap_Firmwares ).

is it possible to write a program which prints its own source code utilizing a "sequence-generating-function"

is it possible to write a program which prints its own source code utilizing a "sequence-generating-function"?
what i call a sequence-generating-function is simply a function which returns a value out of a specific interval (i.e. printable ascii-charecters (32-126)). the point now is, that this generated sequence should be the programs own source-code. as you see, implementing a function which returns an arbitrary sequence is really trivial, but since the returned sequence must contain the implementation of the function itself it is a highly non-trivial task.
this is how such a program (and its corresponding output) could look like
#include <stdio.h>
int fun(int x) {
ins1;
ins2;
ins3;
.
.
.
return y;
}
int main(void) {
int i;
for ( i=0; i<size of the program; i++ ) {
printf("%c", fun(i));
}
return 0;
}
i personally think it is not possible, but since i don't know very much about the underlying matter i posted my thoughts here.
i'm really looking forward to hear some opinions!
If you know how to encode an array as a function (you seem to be saying you already know how to do this) then the Kleene Recursion theorem guarantees it can be done.
But for doubting Thomases, here's a C example. It has a program generating function that uses only +, -, *, / or calls other functions that use them.
Quines are always possible if you have Turing completeness and freedom to print what you like.
What you're referring to is a QUINE. Wiki's article on it is pretty good, with some helpful links. http://en.wikipedia.org/wiki/Quine_%28computing%29
To fly off at a tangent, try looking at Tupper's Self-Referential Formula.

Resources