How to write a (numerical) function using another (numerical) function? - numerical-methods

(This might be a bizarre question, so please don't tell me "why do you want to do this?".)
I'm wondering whether there are methods or tricks or tools or... to write a function using another function (the specific language doesn't really matter). For example, assume that you are given a function "power" defined as follows:
int power (int n) { return n == 0 ? 1 : 2 * power (n - 1); }
and assume that you are asked to write, using that function or (even better) by transforming that function, another one that computes for example the Lucas numbers (2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, ...). Of course the trivial way to use the given function would be to do:
int lucas (int n) { ... + power (n) - power (n) + ... }
but this is not the kind of answer I'm looking for. Likewise the trivial way to transform the function is to delete its body and writing another one instead, but again it's obviously not what I want to do.

Yes.
That is pretty standard in many languages.
Functions take some sort of input parameters and may call other functions or itself, and eventually return some sort of value.
If you have a specific language in mind, someone might show you a
straightforward example.

Related

Can I define a maxima function f(x) which assigns to the argument x

Sorry for the basic question, but it's quite hard to find too much discussion on Maxima specifics.
I'm trying to learn some Maxima and wanted to use something like
x:2
x+=2
which as far as I can tell doesn't exist in Maxima. Then I discovered that I can define my own operators as infix operators, so I tried doing
infix("+=");
"+=" (a,b):= a:(a+b);
However this doesn't work, as if I first set x:1 then try calling x+=2, the function returns 3, but if I check the value of x I see it hasn't changed.
Is there a way to achieve what I was trying to do in Maxima? Could anyone explain why the definition I gave fails?
Thanks!
The problem with your implementation is that there is too much and too little evaluation -- the += function doesn't see the symbol x so it doesn't know to what variable to assign the result, and the left-hand side of an assignment isn't evaluated, so += thinks it is assigning to a, not x.
Here's one way to get the right amount of evaluation. ::= defines a macro, which is just a function which quotes its arguments, and for which the return value is evaluated again. buildq is a substitution function which quotes the expression into which you are substituting. So the combination of ::= and buildq here is to construct the x: x + 2 expression and then evaluate it.
(%i1) infix ("+=") $
(%i2) "+="(a, b) ::= buildq ([a, b], a: a + b) $
(%i3) x: 100 $
(%i4) macroexpand (x += 1);
(%o4) x : x + 1
(%i5) x += 1;
(%o5) 101
(%i6) x;
(%o6) 101
(%i7) x += 1;
(%o7) 102
(%i8) x;
(%o8) 102
So it is certainly possible to do so, if you want to do that. But may I suggest maybe you don't need it? Modifying a variable makes it harder to keep track, mentally, what is going on. A programming policy such as one-time assignment can make it easier for the programmer to understand the program. This is part of a general approach called functional programming; perhaps you can take a look at that. Maxima has various features which make it possible to use functional programming, although you are not required to use them.

Does D std lib include something like boost.fusion and boost.mpl?

I'm still evaluating if i should start using D for prototyping numerical code in physics.
One thing that stops me is I like boost, specifically fusion and mpl.
D is amazing for template meta-programming and i would think it can do mpl and fusion stuff but I would like to make sure.
Even if i'll start using d, it would take me a while to get to the mpl level. So i'd like someone to share their experience.
(by mpl i mean using stl for templates and by fusion, i mean stl for tuples.)
a note on performance would be nice too, since it's critical in physics simulations.
In D, for the most part, meta-programming is just programming. There's not really any need for a library like boost.mpl
For example, consider the lengths you would have to go to in C++ to sort an array of numbers at compile time. In D, you just do the obvious thing: use std.algorithm.sort
import std.algorithm;
int[] sorted(int[] xs)
{
int[] ys = xs.dup;
sort(ys);
return ys;
}
pragma(msg, sorted([2, 1, 3]));
This prints out [1, 2, 3] at compile time. Note: sort is not built into the language and has absolutely no special code for working at compile time.
Here's another example that builds a lookup table for Fibonacci sequence at compile time.
int[] fibs(int n)
{
auto fib = recurrence!("a[n-1] + a[n-2]")(1, 1);
int[] ret = new int[n];
copy(fib.take(n), ret);
return ret;
}
immutable int[] fibLUT = fibs(10).assumeUnique();
Here, fibLUT is constructed entirely at compile time, again without any special compile time code needed.
If you want to work with types, there are a few type meta functions in std.typetuple. For example:
static assert(is(Filter!(isUnsigned, int, byte, ubyte, dstring, dchar, uint, ulong) ==
TypeTuple!(ubyte, uint, ulong)));
That library, I believe, contains most of the functionality you can get from Fusion. Remember though, you really don't need to use much of template meta-programming stuff in D as much as you do in C++, because most of the language is available at compile time anyway.
I can't really comment on performance because I don't have vast experience with both. However, my instinct would be that D's compile time execution is faster because you generally don't need to instantiate numerous templates. Of course, C++ compilers are more mature, so I could be wrong here. The only way you'll really find out is by trying it for your particular use case.

(Ordered) Set Partitions in fixed-size Blocks

Here is a function I would like to write but am unable to do so. Even if you
don't / can't give a solution I would be grateful for tips. For example,
I know that there is a correlation between the ordered represantions of the
sum of an integer and ordered set partitions but that alone does not help me in
finding the solution. So here is the description of the function I need:
The Task
Create an efficient* function
List<int[]> createOrderedPartitions(int n_1, int n_2,..., int n_k)
that returns a list of arrays of all set partions of the set
{0,...,n_1+n_2+...+n_k-1} in number of arguments blocks of size (in this
order) n_1,n_2,...,n_k (e.g. n_1=2, n_2=1, n_3=1 -> ({0,1},{3},{2}),...).
Here is a usage example:
int[] partition = createOrderedPartitions(2,1,1).get(0);
partition[0]; // -> 0
partition[1]; // -> 1
partition[2]; // -> 3
partition[3]; // -> 2
Note that the number of elements in the list is
(n_1+n_2+...+n_n choose n_1) * (n_2+n_3+...+n_n choose n_2) * ... *
(n_k choose n_k). Also, createOrderedPartitions(1,1,1) would create the
permutations of {0,1,2} and thus there would be 3! = 6 elements in the
list.
* by efficient I mean that you should not initially create a bigger list
like all partitions and then filter out results. You should do it directly.
Extra Requirements
If an argument is 0 treat it as if it was not there, e.g.
createOrderedPartitions(2,0,1,1) should yield the same result as
createOrderedPartitions(2,1,1). But at least one argument must not be 0.
Of course all arguments must be >= 0.
Remarks
The provided pseudo code is quasi Java but the language of the solution
doesn't matter. In fact, as long as the solution is fairly general and can
be reproduced in other languages it is ideal.
Actually, even better would be a return type of List<Tuple<Set>> (e.g. when
creating such a function in Python). However, then the arguments wich have
a value of 0 must not be ignored. createOrderedPartitions(2,0,2) would then
create
[({0,1},{},{2,3}),({0,2},{},{1,3}),({0,3},{},{1,2}),({1,2},{},{0,3}),...]
Background
I need this function to make my mastermind-variation bot more efficient and
most of all the code more "beautiful". Take a look at the filterCandidates
function in my source code. There are unnecessary
/ duplicate queries because I'm simply using permutations instead of
specifically ordered partitions. Also, I'm just interested in how to write
this function.
My ideas for (ugly) "solutions"
Create the powerset of {0,...,n_1+...+n_k}, filter out the subsets of size
n_1, n_2 etc. and create the cartesian product of the n subsets. However
this won't actually work because there would be duplicates, e.g.
({1,2},{1})...
First choose n_1 of x = {0,...,n_1+n_2+...+n_n-1} and put them in the
first set. Then choose n_2 of x without the n_1 chosen elements
beforehand and so on. You then get for example ({0,2},{},{1,3},{4}). Of
course, every possible combination must be created so ({0,4},{},{1,3},{2}),
too, and so on. Seems rather hard to implement but might be possible.
Research
I guess this
goes in the direction I want however I don't see how I can utilize it for my
specific scenario.
http://rosettacode.org/wiki/Combinations
You know, it often helps to phrase your thoughts in order to come up with a solution. It seems that then the subconscious just starts working on the task and notifies you when it found the solution. So here is the solution to my problem in Python:
from itertools import combinations
def partitions(*args):
def helper(s, *args):
if not args: return [[]]
res = []
for c in combinations(s, args[0]):
s0 = [x for x in s if x not in c]
for r in helper(s0, *args[1:]):
res.append([c] + r)
return res
s = range(sum(args))
return helper(s, *args)
print partitions(2, 0, 2)
The output is:
[[(0, 1), (), (2, 3)], [(0, 2), (), (1, 3)], [(0, 3), (), (1, 2)], [(1, 2), (), (0, 3)], [(1, 3), (), (0, 2)], [(2, 3), (), (0, 1)]]
It is adequate for translating the algorithm to Lua/Java. It is basically the second idea I had.
The Algorithm
As I already mentionend in the question the basic idea is as follows:
First choose n_1 elements of the set s := {0,...,n_1+n_2+...+n_n-1} and put them in the
first set of the first tuple in the resulting list (e.g. [({0,1,2},... if the chosen elements are 0,1,2). Then choose n_2 elements of the set s_0 := s without the n_1 chosen elements beforehand and so on. One such a tuple might be ({0,2},{},{1,3},{4}). Of
course, every possible combination is created so ({0,4},{},{1,3},{2}) is another such tuple and so on.
The Realization
At first the set to work with is created (s = range(sum(args))). Then this set and the arguments are passed to the recursive helper function helper.
helper does one of the following things: If all the arguments are processed return "some kind of empty value" to stop the recursion. Otherwise iterate through all the combinations of the passed set s of the length args[0] (the first argument after s in helper). In each iteration create the set s0 := s without the elements in c (the elements in c are the chosen elements from s), which is then used for the recursive call of helper.
So what happens with the arguments in helper is that they are processed one by one. helper may first start with helper([0,1,2,3], 2, 1, 1) and in the next invocation it is for example helper([2,3], 1, 1) and then helper([3], 1) and lastly helper([]). Of course another "tree-path" would be helper([0,1,2,3], 2, 1, 1), helper([1,2], 1, 1), helper([2], 1), helper([]). All these "tree-paths" are created and thus the required solution is generated.

How can I reproduce a scribbly pattern like this in code?

I made this graph in wolfram alpha by accident:
Can you write code to produce a larger version of this pattern?
Can you make similar looking patterns?
Readable code in any language is good, but something that can be run in a browser would be best (i.e. JavaScript / Canvas). If you write code in other languages, please include a screenshot.
Notes:
The input formula for the above image is: arg(sin(x+iy)) = sin^(-1)((sqrt(2) cos(x) sinh(y))/sqrt(cosh(2 y)-cos(2 x))) (link)
You don't have to use to use the above formula. Anything which produces a similar result would be cool. But "reverse engineering" Wolfram Alpha would be best
The two sides of the equation are equal (I think), So WA should have probably only returned 'true' instead of the graph
The pattern is probably the result of rounding errors.
I don't know if the pattern was generated by iterating over every pixel or if it's vector based (points and lines). My guess is with vector.
I don't know what causes this type of pattern ('Rounding errors' is the best guess.)
IEEE floating point standard does not say how sin or cos, etc should work, so trig functions vary between platforms and architectures.
No brownian motion plots please
Finally, here's another example which might help in your mission: (link)
As you asked for similar looking patterns in any language, here is the Mathematica code (really easy since Wolfram Alpha is based on Mathematica)
Edit
It is indeed a roundoff effect:
If we set:
and make a plot
Plot3D[f[x, y], {x, 7, 9}, {y, -8, -9},WorkingPrecision -> MachinePrecision]
The result is:
But if we extend the precision of the plot to 30 digits:
Plot3D[f[x, y], {x, 7, 9}, {y, -8, -9},WorkingPrecision -> 30]
We get
and the roughness is gone (which caused your scribbly pattern)
BTW, your f[x,y] is a very nice function:
So if I managed to copy your formulas without errors (which should be considered a miracle), both sides of your equation are equal only in certain periodic ranges in x, probably of the form [2 n Pi, (2 n + 1) Pi]

What is the name of this data structure or technique of using relative difference between sequence members

Let's say I have a sequence of values (e.g., 3, 5, 8, 12, 15) and I want to occasionally decrease all of them by a certain value.
If I store them as the sequence (0, 2, 3, 4, 3) and keep a variable as a base of 3, I now only have to change the base (and check the first items) whenever I want to decrease them instead of actually going over all the values.
I know there's an official term for this, but when I literally translate from my native language to English it doesn't come out right.
Differential Coding / Delta Encoding?
I don't know a name for the data structure, but it's basically just base+offset :-)
An offset?
If I understand your question right, you're rebasing. That's normally used in reference to patching up addresses in DLLs from a load address.
I'm not sure that's what you're doing, because your example seems to be incorrect. In order to come out with { 3, 5, 8, 12, 15 }, with a base of 3, you'd need { 0, 2, 5, 9, 12 }.
I'm not sure. If you imagine your first array as providing the results of some function of an index value f(i) where f(0) is 3, f(1) is 5, and so forth, then your second array is describing the function f`(i) where f(i+1) = f(i) + f'(i) given f(0) = 3.
I'd call it something like a derivative function, where the process of retrieving your original data is simply the summation function.
What will happen more often, will you be changing f(0) or retrieving values from f(i)? Is this technique rooted in a desire to optimize?
Perhaps you're looking for a term like "Inductive Sequence" or "Induction Sequence." (I just made that up.)