# How to create a loop with two variables?

I have defined the following functions:

def I(x):
return 1

def Moebius(x):
return sum(moebius(i) * I(x*i^(-1)) for i in range(1,x+1))


The output is of course Mertens function. How do I turn Moebius(x) into an operator, so that I can define Moebius^2(x) as the Moebius transform of the output?

edit retag close merge delete

Sort by ยป oldest newest most voted

First, the * I(x*i^(-1)) part in your Moebius function will only add some useless computation since it is a multiplication by 1.

Then, you can define the composition of your Moebius function by itself as follows:

M2 = lambda x : Moebius(Moebius(x))


If you want the ^2 notation to work, you have to define a Python class since ^2 calls the __pow__ method of your object, this will require some more work around the following lines:

class MyOperator():
def __init__(self, func):
self.func = func
def __pow__(self, exponent):
def iterfunc(x):
result = x
for i in range(exponent):
result = self.func(result)
return result
return MyOperator(iterfunc)
def __call__(self, x):
return self.func(x)


Then you can do:

sage: f = MyOperator(Moebius)
sage: f(10)
-1
sage: g = f^2
sage: g(10)
0
sage: f(f(10))
0


Or similarly:

sage: inc = lambda x : x+1
sage: f = MyOperator(inc)
sage: f(14)
15
sage: g = f^12
sage: g(14)
26
sage: h = f^0
sage: h(100)
100

more

Thank you very much for such a prompt and clear reply. The I function was there because I'd hoped to have it as non-trivial input to the function.

( 2015-01-03 06:51:31 -0600 )edit

Without the presence of a function such as I(x), I don't see how Moebius even has an input ( other than x). Can you explain how your solution had another input please? Thank you

( 2015-01-03 08:37:26 -0600 )edit

You could just write

def Moebius(x):
return sum(moebius(i) for i in range(1,x+1))


Which other input than x would you like ?

( 2015-01-06 01:07:12 -0600 )edit

Excuse my absolute ignorance of programming- though I am now certain this is complete nonsense from sage's point of view, in an algebraic sense, I want the function I(x) to be something in the domain of the operator that I name Moebius. The reason I set I(x) to be constant initially was merely to demonstrate that I get the right output in this case. What I really want to do is take the output as an input to further applications of Moebius, so that I get the higher order Mertens functions, that is, the Mellin transforms of the negative powers of the Riemann zeta function. Of course there ought to be another way to do this involving extracting the number of times each primes divides a given integer, but that looked rather more difficult at first. It's equally likely that I am mistaken about that too though.

( 2015-01-18 04:56:44 -0600 )edit