text:
# All Questions

83,855 questions
Filter by
Sorted by
Tagged with
143 views

### Getting the "correct" branch of a complex function

This stuff always trips me up. I'm trying to plot a function and I think that the plot looks good in one region and isn't really what I'm expecting in another: The right side of the plot is what I am ...
• 1,448
1 vote
51 views

### Making text larger without changing size of superscript?

I have the following plot: ...
• 391
32 views

For FindFit I want to have a norm that just sums up all residuals. For the sum of absolute values there is NormFunction -> (Norm[#, 1] &), but I don't know ...
• 77
118 views

### How to integrate this product of Exp[] and Cos[] using Mathematica

I would like to integrate the following product of Exp and Cos： ...
• 699
82 views

### How to determine if a group H is a normal subgroup of group G?

A subgroup $H$ of the group $G$ is normal group in $G$ if and only if $\displaystyle ghg^{-1}\in H$ for all $\displaystyle g\in G$ and $\displaystyle h\in H$. How to use MMA to know the group $H$ is a ...
• 23.1k
69 views

### How to solve this second-order nonlinear ordinary differential equation using the explicit runge kutta method [closed]

It its my first time using mathematica so I am very unfamiliar with the syntax. I have gathered pieces of codes to solve this system of second order non-linear Diff.Eq. : ...
151 views

### How to speed up the calculation of recurrence formula?

I have a recurrence formula. How to quickly solve P[1] to p[49]? ...
• 107
109 views

### Evaluating PlusMinus to 2 decimal answers

How do I evaluate and expand an expression containing PlusMinus such that: N[PlusMinus[1, 1]] returns 2, 0 I'm stuck at ...
68 views

### Replacement, PatternTest, Module related Question

Let's see how MMA handles following type of expression : Replace[L, {pattTest1->rhs1, pattTest2->rhs2, pattTest3->rhs3}, {1}] Specific example : ...
• 2,451
1 vote
70 views

...
• 43
67 views

### InverseLaplaceTransform gives inconsistent results

These should give the same results, but they do not: InverseLaplaceTransform[1/Sqrt[x] HeavisideTheta[x + 1], x, y] InverseLaplaceTransform[1/Sqrt[x], x, y] ...
• 2,721
72 views

### Animate a point that follows a function inside a plot

I'm trying to create a plot that shows an animation of a point moving along a function. The idea behind this is that a I want the point to follow the function until the discontinuity point. For every ...
• 69
134 views

### Empty .png figures generated by a function "PlotWithGrid" whereas no problem with Export function

I have an issue about a .wls script that I can't manage to solve for the moment. I execute it with wolframscript interpeter on ...
• 43
83 views

### Find global maximum of InterpolatingFunction in interval but not maximum value

I have InterpolatingFunction generated from experimental data with many local maxima, one major peak I need to find, and the tail that grouse much higher then major peak. I tried to find my peak with ...
• 3,199
78 views

### Classifying elements, by the value of a fixed function, using Replace

Let L be a list of several lists. And the length of each list is less than 1000. You can create L by ...
• 2,451
43 views

### Why does Mathematica not know some integrals diverge?

I want to analyse the convergence of some complicated 1d integrals that may have divergences at $x=0$, similarly to the harmonic integral $\int_0^a 1/x \ \mathbb{d} x$, which I know is divergent. When ...
273 views

### Sorting a list of "Low", "Medium", "High" into low, medium, high

I have a list with 10.000 entries containing "low", "medium" & "high" data. It is in random order. How can I sort that to low, medium high?
• 43
1 vote
85 views

### MaTeX stopped working after a TeX upgrade

My system: Windows 10, Mathematica 11.2 Yesterday I had to upgrade my MikTeX because I absolutely needed to compile a document needing a newer version. Today MaTeX stopped working. I started getting ...
233 views

### Solve differential equation with constant

How can I get a symbolic solution from the following differential equation? I don't know in that case using a change of variable is a good idea. I have tried in maple as well but the form of the ...
• 31
121 views

### Estimating values from a timeseries picture

I have the following picture (one of several hundred): I want to basically read out every y-value for every year on the x-axis from this graphic and create a data table from it. For example, I want ...
• 2,703
32 views

### How to label lines and adjust ticks in MultiaxisArrangement?

I see we can make multi-axes with MultiaxisArrangement, but how can we adjust the ticks and how to label the lines in it or how to place plot legends of those lines?...
• 173
34 views

### ParametricPlot Evaluate a fuction with two parameters

I am trying to evaluate and plot a parametric function by altering the initial conditions with two parameters. The evaluation parts works ok but i am having problem plotting it. I tried to use Flatten ...
• 31
1 vote
58 views

### How to introduce a symbol for the derivative as a symbol with a point on top?

I am making images in Mma for an article. In a FrameLabel I need to show a text containing a derivative in form of the letter X with a point on top: I found a special button in Palette "Writing ...
• 34.8k
1 vote
53 views

### Append data in for loop in table shape

I'm trying to append for every element of my for loop a complete table to my file myfile.dat, but everytime I run the loop I get it overwritten by the last cycle. ...
1 vote
67 views

### Module returns multiple functions

I want to write a module that returns two functions which then can be evaluated later on. I know how to do it with a single function, but I don't know how to make it work for multiple functions. An ...
• 113
103 views

...
• 41
62 views

### Simplifying an expression(s) for an equilibrium point?

Trying to use Bob Hanlon's solution from here for the following system doesn't seem to work here, why? How do I simplify the equilibrium point to this simplified expression? ...
• 465
117 views

### Pattern match with "+" sign

Can you pattern match with a "+" sign? Here is the recursion...(which does not work) ...
• 341
1 vote
63 views

Motivation: I am using FunctionInterpolation[COMSOL[x]] in combination with COMSOL to search for the interpolation of my COMSOL model. COMSOL needs a lot of time to ...
564 views

### How can I quickly find the coordinates of key points? [closed]

There are 1000 points in the space. The coordinates are (0,0,0) - (9,9,9). Any point can cover all points on the three straight lines (parallel to the X, Y and Z axes respectively) where this point is ...
• 107
1 vote
151 views

• 187
40 views

...
318 views

### Reproducing figure from paper on hydrodynamics

I am trying to solve Eqn. on Page 674 of https://www.nature.com/articles/nphys3667.pdf I shall quote the relevant paragraph : Next, we proceed to analyse the nonlocal response in a strip with ...
• 327
155 views

### How to draw a heat map for some data across a circular region?

I have the following data over a circular region like this: How can I make a heat map across the circular area?
59 views

### How to Bring the XY Contour Plot Inside a ListPointPlot3D

The code below nicely takes 10000 pairs of {x,y,z} coordinates generated by a system of recurrence equations and plots them as ListPlot3D and ListPointPlot3D. I would like to incorporate the xy ...
• 1,039
112 views

### Bugs in hypergeometric functions with negative integer lower parameters

If you were to evaluate these expressions, Mathematica returns the value shown. ...
• 61
83 views

### Solve a symbolic expression

I'm working with the Hoek Brown plastic yield surface to model soil/rock materials. The yield surface is given by: Were sig1 and sig3 are the maximum and minimum principal stresses. sigc, m, s and n ...
• 2,760
36 views

### Plotting a tangent line [duplicate]

I have to plot a function and the tangent line and I don't know how to do it. It has to be one plot function: f[x_]= Sin[x] and the tangent line for the function is x=0 Other questions didn't help me ...
35 views

### Wolfram script exported from a Mathematica Notebook : errors actually warnings?

I have exported with the following script put at the beginning of my Mathematica notebook : ...
• 35
58 views

### NDSolve: there are more variables than equations, underdet

I am working on using NDSolve to solve coupled ODE. The following is the coupled equations. It works fine for sever orders. I used table to generate like 962 couple variables and equations, where the ...
59 views

### Create a Table with 3 different variables from 2 Lists and 1 Table

I am new to Mathematica. I learned how to join 2 lists to make (x,y) type of representation using Transpose@{X,Y}. Now my problem is that I have to make a table of 3 variables. I have one set of data ...
85 views

### Extremely slow import of mx files with Molecule objects [closed]

Version: 13.0.1 on Linux Hello, I recently found a collection of 39,361 SMILES strings that I converted to Molecule format with Mathematica. I then exported the resulting list of Molecule objects into ...
• 515
1 vote
89 views

### While inside a function body does not work as expected [closed]

I'm trying to write a function that return a randomly created rational polynomial function that has a discontinuities points. I already have a function that generates random rational polynomial (...
• 69


text:
# Energy conservation: Bullet-block collision

n.hirsch1

## Homework Statement

A 2.30 g bullet embeds itself in a 1.6 kg block, which is attached to a spring of force constant 770 N/m.
A) If the maximum compression of the spring is 5.40 cm, find the initial speed of the bullet.

## Homework Equations

Step one: convert everything to kg and m
Step two: 1/2 mvi^2 = 1/2 kA^2

## The Attempt at a Solution

I first tried to solve the above equation for vi, and then plug in the rest since m, k, and A are given, but this gave me 29.1 m/s and that is not the correct answer. I am not sure where else to go with this, this is the only equation I know that deals with initial velocity!

Homework Helper
Your conservation of energy equation should be correct for the compression stage, so you can find the initial speed of the bullet/block combination that way (much less than 29 m/s). Use conservation of momentum in the bullet-block collision stage.

Homework Helper
Sounds like the correct method, check your calculations

1/2 mvi^2 = 1/2 kA^2

0.0023 v^2 = 770 * 0.054
v = sqrt (770 * 0.054/0.0023) = 134m/s

n.hirsch1
134 m/s isn't correct either. I don't understand what is wrong with this equation, everything is given.
I can't use conservation of momentum for inelastic collisions because I don't have a final velocity.

Homework Helper
You do have the final velocity - it says maximum compression of the spring = block is stationary

n.hirsch1
mgb_phys: I must be looking at the wrong equation. for conservation of momentum, if the final velocity of the system is zero (which it is), and it is an inelastic collision, then the equation is :
vf = m1vi +m2vi / m1 + m2
and m2vi is equal to zero since its at rest, so
mvi = (m + M) vf
and if the whole system goes to rest, then everything is zero!!

Homework Helper
You can use conservation of momentum to find the initial velocity of bullet + block and then use conservation of energy to find the kinetic to spring energy but this seems a little pointless if you are assuming elastic collisions then the ke of the bullet becomes the spring energy.

Homework Helper
For the spring compressing:
1/2 mvi^2 = 1/2 kA^2
vi = sqrt(kA²/m) = sqrt(770*.054²/1.623) = 1.176 m/s

Now you know the speed of the bullet + block after the collision.
Use conservation of momentum to work back to the speed of the bullet before the collision. This collision cannot be elastic because the bullet embeds itself into the block with very much friction!

format: plain


text:
# Tag Info

66

Logical AND: Use the linear constraints $y_1 \ge x_1 + x_2 - 1$, $y_1 \le x_1$, $y_1 \le x_2$, $0 \le y_1 \le 1$, where $y_1$ is constrained to be an integer. This enforces the desired relationship. (Pretty neat that you can do it with just linear inequalities, huh?) Logical OR: Use the linear constraints $y_2 \le x_1 + x_2$, $y_2 \ge x_1$, $y_2 \ge x_2$, ...

19

The logical AND relation can be modeled in one range constraint instead of three constraints (as in the other solution). So instead of the three constraints $$y_1\geq x_1+x2−1,\qquad y_1\leq x_1,\qquad y_1\leq x_2\,,$$ it can be written using the single range constraint $$0 \leq x_1 + x_2-2y_1 \leq 1\,.$$ Similarly, for logical OR: $$0 \leq 2y_1 - x_1 - x_2 ≤... 16 If a problem is NP-Hard it means that there exists a class of instances of that problem whose are NP-Hard. It is perfectly possible for other specific classes of instances to be solvable in polynomial time. Consider for example the problem of finding a 3-coloration of a graph. It is a well-known NP-Hard problem. Now imagine that its instances are restricted ... 12 No, special cases can be easier. Consider this IP, for example, given a_i \geq 0 for i \in [1..n]: \qquad\displaystyle \min \sum_{i=1}^n x_ia_i s.t. \quad\displaystyle\sum_{i=1}^n x_i \geq 1 and \ \displaystyle x_i \in \mathbb{N} for i \in [1..n]. It finds the minimum among a_1, \dots, a_n (that for which, inevitably, x_i=1 in an optimal ... 11 0-1 ILP formulated as: Does there exist a vector \mathbf{x}, subject to constraints:$$ \left.\begin{array}{rrrrr|rr} a_{11} x_1 & + &a_{12} x_2 & ... + & a_{1n} x_n\le b_1 \\ a_{21} x_1 & + &a_{22} x_2 & ... + & a_{2n} x_n\le b_2 \\ ...\\ a_{m1} x_1 & + &a_{m2} x_2 & ... + & a_{mn} ...

10

This problem is NP-hard by reduction from Vertex Cover. In the Vertex Cover problem, we are given a graph $G = (V, E)$ and a number $r$, and our task is to determine whether there is some subset $U$ of at most $r$ vertices from $V$ such that every edge in $E$ is incident on at least one vertex in $U$. (Equivalently: Is it possible to kill every edge in $G$ ...

9

A classical result of Berlekamp, McEliece, and van Tilborg shows that the following problem, maximum likelihood decoding, is NP-complete: given a matrix $A$ and a vector $b$ over $\mathbb{F}_2$, and an integer $w$, determine whether there is a solution to $Ax = b$ with Hamming weight at most $w$. You can reduce this problem to your problem. The system $Ax = ... 8 All constraints in a linear program are convex (if$x,y$satisfy the constraints, then$tx+(1-t)y$also does for all$0 \leq t \leq 1$). The constraint$|a|+b > 3$is not convex, since$(4,0)$and$(-4,0)$are both solutions while$(0,0)$is not. It is also not closed, which is another reason why you cannot use it in a linear program (change$>$to$\...

8

Some ILPs can be solved rapidly (to an exact solution) in practice; some cannot. Usually when we are talking about solving an ILP, we are looking for an exact solution, though some ILP solvers can find an approximate solution as well (find the best solution they can within the time constraints). There are no hard-and-fast rules. Of course, ILP is NP-hard, ...

7

Yes, there is a polynomial-time algorithm for your problem. There's no need to use a LP or ILP; you can solve it directly using combinatorial, graph-based methods. In particular, we can solve your problem by a reduction to the assignment problem, i.e., to computing a maximum weight matching in a weighted bipartite graph. Suppose we have a bipartite graph ...

6

I've found out a very interesting document that answers my question: http://lpsolve.sourceforge.net/5.5/absolute.htm It's about integer programming and it covers all possible cases I think. See section >= minimum to handle abs(X) >= minimum. Here is another one with more tricks: http://orinanobworld.blogspot.de/2012/07/modeling-absolute-values.html There ...

6

In $\mathbb R$, one can simply round down or round up to obtain an element of $\mathbb Z$. Only two choices! However, in $\mathbb R^n$, one has $2^n$ ways of rounding to obtain an element of the integer lattice $\mathbb Z^n$. For example, if $n=100$, one has $2^{100} \approx 10^{30}$ possible ways of rounding. Of course, one can round all entries of an $n$...

6

There is unlikely to be any efficient algorithm. Your first class of constraints are monotone exactly-1 CNF clauses. Your second class of constraints are monotone CNF clauses. The monotone part indicates that negated literals aren't allowed (you can't have $x_1 - x_3 = 1$ or $x_1 - x_4 \ge 1$). Thus, in the special case where you have only type-2 ...

6

First of all, let me start by making clear that the notion of 'solvable in polynomial time' is something defined on a class of problem instances. It makes no sense to speak of polynomial time for a single problem as any single problem can be solved in $O(1)$! That said, there is a notable class of ILP's that is known to be polynomial time solvable. This ...

5

Sure, of course you can create random linear programming problems. Why not? Yes, in general, you can usually verify the solution to a linear programming problem faster than you can find the solution. Verifying the solution just involves plugging into the equations and checking that all equations hold. Finding the solution requires a bit more work (e.g., ...

5

All four problems are NP-complete. Let me start by proving two easy results: Your problem #3 is NP-complete, even when the matrix has only a single row, as explained here: Complexity of a subset sum variant. This implies that #4 is NP-complete as well, as #3 is a special case of #4. Now for the strong result: Your problem #1 is NP-complete. The proof of ...

5

Simplifying the problem: Given a positive integer $r$ positive integers $m, n \geq 2$ a partial binary matrix $\mathrm A \in \{*, 0,1\}^{m \times n}$ (where $*$ denotes an unknown entry) determine whether it is possible to complete the given partial matrix $\mathrm A$ with values in $\{0,1\}$ such that the resulting completed matrix ...

5

It's the same was for all NP problems; the optimisation problem is Find a valid solution $s$ that minimises¹ $f(s)$! and the corresponding decision problem is Is there a valid solution $s$ with $f(s) \leq k$? You see that the former immediately solves the latter, and you can solve the former by using the latter with binary search over the set of ...

5

If there are only constraints that place a lower bound on the number of trucks, but no constraints that place an upper limit on the number of trucks, then of course you can round up. That will still give you a solution. However, there are multiple caveats: First, this isn't always possible. Sometimes there are both constraints that place lower limits and ...

5

You could add a constant $0<A<M$ and then you add this constraint: $$A-y(A+M)\leqslant x_1-x_2\leqslant M(1-y).$$ If $y=1$ then you are left with $$-M\leqslant x_1-x_2\leqslant 0,$$ which says that $x_1\leqslant x_2$. And if $y=0$ then you will be left with $$A\leqslant x_1-x_2\leqslant M,$$ which says that $x_1>x_2$ (since $0<A<M$).

5

This can be expressed with just the equation $X=Y$. Since $X,Y$ are zero-or-one variables, the only possible assignments that are consistent with your condition are $X=Y=0$ and $X=Y=1$. See Express boolean logic operations in zero-one integer linear programming (ILP) for many more boolean conditions and how to express them as linear inequalities.

5

The notion of duality suggested by the discrete Farkas lemma found in Lasserre's paper does not correspond to an integer program. There is a notion of duality for integer programs (see for example here), but strong duality does not hold, so I doubt it can be used along the lines you suggest.

5

The decision problem version of integer linear programming is known to be in NP. In particular, determining whether an integer linear program has a feasible solution is in NP. It is known that if an integer linear program has a feasible solution, then it has a feasible solution whose length (in bits) is at most a polynomial in the length (in bits) of the ...

4

One-in-three 3SAT is NP-complete. Looking at the reduction, it inherits the APX-hardness of 3SAT. You can formulate one-in-three 3SAT as a binary integer program with binary entries, so you problem is APX-hard.

4

I have a method for you that will help you find valid solutions (matrices) for many possible values of $m,n$. However, it is not a complete answer to your question. It can try to find a matrix for a particular value of $m,n$, but it might fail, and if it fails, you've learned nothing; my method cannot prove that no such matrix exists. The method is based ...

4

Yes, some IP formulations are less useful than others. The technique used to show that an LP relaxation can only be so good is showing integrality gaps. For a minimization problem, an integrality gap of $k$ in an instance in which the optimal integer solution has value $V$ but the LP has a solution of value at most $V/k$. This shows that any rounding ...

4

The existence of such a reduction follows immediately from the Cook-Levin theorem, which guarantees that you can reduce any problem in NP to SAT and describes explicitly one way to do it. Just work through the steps of the proof of the theorem (which can be found in any textbook) and you'll obtain a valid reduction from 0-1 ILP to SAT.

4

You can do this by introducing the two inequalities $$x_1 \le x_2 + M (1-y)$$ and $$x_1 > x_2 - M y.$$ The former encodes the requirement $y=1 \implies x_1 \le x_2$ (you can see that if $y=1$, then the $M(1-y)$ term disappears; if $y=0$, then $M(1-y)$ becomes something huge and the inequality is automatically satisfied). The latter encodes the ...

4

Maybe there is something I do not understand in your question, but the way it is formulated it seems that the set of solutions is: set $b_i=1$ if $x_i > 0$ set $b_i=0$ if $x_i < 0$ all others $b_i$ can either be zero or one It is clear that any other assignment will give you a lower value (either by adding a positive value or not adding a positive ...

Only top voted, non community-wiki answers of a minimum length are eligible


text:
# Approximation of functions defined on the grid $\{0, \delta, 2\delta, \ldots\}$ by Fourier-Meixner sums

### DOI: 10.31029/demr.7.7

The present paper is devoted to the study of approximation properties of partial sums of the Fourier series in the modified Meixner polynomials $M_{n,N}^\alpha(x)=M_n^\alpha(Nx)$ $(n=0, 1, \dots)$ which for $\alpha>-1$ constitute an orthogonal system on the grid $\Omega_{\delta}=\{0, \delta, 2\delta, \ldots\}$, where $\delta=\frac{1}{N}$, $N>0$ with weight $w(x)=e^{-x}\frac{\Gamma(Nx+\alpha+1)}{\Gamma(Nx+1)}$. The main attention is paid to obtaining an upper estimate for the Lebesgue function of these partial sums.

Keywords: Meixner polynomials, Fourier series, Lebesgue function.


text:
# Find nearest tile of type x

I currently have an array of tiles which makes up the tilemap (stored as an int array) and I want an NPC to be able to move itself to the nearest tile of type X (ie find the nearest tree and chop it down). What's the best algorithm to use to find the nearest tile of a certain type given a location (x,y)?

Problems like this can easily be solved by using Dijkstra's algorithm. See this answer for an explanation of how it works.

The others suggested a flood-fill, but that won't work (or at least won't be optimal) if there are obstacles (not trees) somewhere along the path. If there are only a few items to find, you could also use A* with an appropriate heuristic (eg. min. straight-line distance to items).

Update: If you don't want to implement Djikstra's algorithm yourself but have an A* implementation in your path-finding library, you could also set the A* heuristic to a constant value (eg. that it always returns 0). That way, A* will behave the same as Djikstra's.

Also note that in the examples I linked to, there's usually one goal-node to find. But it works just as well when searching for a "type" of node (just end the search whenever you find a tile of your desired type).

• Dijkstra's is the right way to go for simple pathfinding. It works even better if the tiles have different travel speeds, like moving over a paved path is faster than moving over grassland. If, on the other hand, you have a huge tileset and Dijkstra's is taking too long, then use A*. Jul 3 '12 at 13:21
• @stevehb It's not really about the size of the tileset (amount of nodes) or "simple" vs. "complex" pathfinding. A* is using a heuristic to predict the best direction to go, thus potentially speeding up the search drastically. If you're searching for any tile of type X, then applying a good heuristic might be less efficient or even impossible compared to an uninformed search such as Djikstra's. Jul 3 '12 at 13:36

If you know absolutely nothing about where such a tile could be I would suggest a sort of breadth first style floodfill:

PathNode start;
PathNodeType query; // the type we are looking for
Queue<PathNode> queue; // gives us a breadth first style search
HashSet<PathNode> visited; // tiles we already visited
queue.Push(start)

while(queue.Count > 0){
PathNode current = queue.Pop();
foreach(PathNode neighbour in current.Neighbours)
{
if(!visited.Contains(neighbour))
{
if(neighbour.Type == query)
{
return neighbour;
}
else if(neighbour.IsWalkable)
{
queue.Push(neighbour);
}
}

}
}

This algorithm first searches the tiles closest to start and then starts circling wider and wider over the walkable tiles until a tile of the given tile is found. By first checking if a neighbour tile is of the given type and only then checking if it is walkable we can also found tiles that are next to walkable tiles but arent walkable itself.

• My words exactly. I'll just add a nice way of visualizing the algorithm: it behaves as if you started pouring water on your starting tile, which then flows into adjacent (accessible) tiles in all directions. (Hence, 'floodfill'.) The first tile of the sought type to be flooded is your nearest match.
– ver
Jul 3 '12 at 6:32
• You should keep in mind, though, the special case here - when there are multiple equidistant tiles of the target type. (I.e. they are the same distance from your starting tile.) The algorithm provided by @RoyT just returns whichever one is first chosen by the PathNode.Neighbours implementation.
– ver
Jul 3 '12 at 6:36
• You need some sort of "visited" flag, otherwise your code will loop endlessly. Also this approach will fall short (won't find the optimal path) if there are obstacles to consider. Jul 3 '12 at 6:42
• @bummzack yes, it may not find the optimal path, but that's irrelevant. The asker wanted an algorithm for finding the nearest tile that specifies the given condition; not a pathfinding one.
– ver
Jul 3 '12 at 7:08
• In a tile-based environment, this flood-fill is basically an implementation of Djikstra's anyway. It just needs to keep track of costs to also get the path to the found tile (to satisfy the requirement of the OP: "I want an NPC to be able to move itself to the nearest tile of type X"). Jul 3 '12 at 7:35

One approach is a simple breadth first search. If you've heard of A*, this is sort of the basis for that algorithm. Except you don't have a known goal location, so you can't direct the search in any one direction So you search all directions at once! There's some implementation details and nice little examples for tile based games here.

Could you add some more details like what language you are in? I mean I guess there could be a general algorithm.

If you have these different tiles in classes per se, you could add a move function in your NPC class or method. It would have to "see" the tile, so you could give it a tile radius and say if anything within X amount of squares of the NPC is this ID type of tile, then move to its x and y location.

An example in an OO language like Java:

    public Tile Tree;

Tree.cutTree(NPC.getX, NPC,getY, Tree.getX, Tree.getY)

public void cutTree(int NPCX, int NPCY, int treeX, int treeY)
{
if(treeX >= NPCX >= 5)
{
if(treeX >= NPCX >= 5)
{
NPC.move(treeX - 1, treeY - 1);
}
}
}

Again I don't know EXACTLY what numbers to add and whether you have a move() function, but basically I would use the x and y position of the two tiles (if you can access each tree tile in the array).

The if statements are where I would use like the edge of the frame or screen but you have to remember if the map of tiles is big enough you could be accessing a tree tile across the map.


text:
# 1/12x+8/12=9

## Simple and best practice solution for 1/12x+8/12=9 equation. Check how easy it is, and learn it for the future. Our solution is simple, and easy to understand, so dont hesitate to use it as a solution of your homework.

If it's not what You are looking for type in the equation solver your own equation and let us solve it.

## Solution for 1/12x+8/12=9 equation:

1/12x+8/12=9
We move all terms to the left:
1/12x+8/12-(9)=0

Domain of the equation: 12x!=0
x!=0/12
x!=0
x∈R

determiningTheFunctionDomain
1/12x-9+8/12=0
We calculate fractions
-9!=0
There is no solution for this equation

`

## Related pages

5.5.102cos 2 xsolve 3x2 4x 2roman numerals for 2002secx tanx dx5x 2 3x 2derivative ln 3x68qcommon multiples of 5 and 8factorization calculatoreighty four is what percent of 212what are the prime factors of 385derivative of tan 2x1990 roman numeral140 prime factorizationderivative of cos3x1 cos 12x360-268adding mixed number fractions calculatorgraph 4x x 2the prime factorization of 858yi12logln x-3 graphsolve equation with fractions calculatorsqrt 3 3equation calculator fractionssolve 2x 6 10multiplying fraction calculatorprime factorization of 792what is the prime factorization of 71sin 6x sin 4x8.1.3prime factorization 104simplify 8x 4xtan sqrt32x 2 3x 1 factoredexpand 2x 2y 574-252sinxqmct6 0easy 97.9lcm of 3 and 2prime factorization for 216what is the prime factorization of 53x2-1 factored1-0.01what is the prime factorization of 825simplify x 3-27sin 3pilog5 x 3derive sin 2xx squared 4xantiderivative sin 3x1.6875 as a fraction2x 4 factored9abcfactor 6x 2 11x 3derivative of 9x4izfactorise a 3 b 3common multiples of 6 and 7log2 log5sin3xwhat is the greatest common factor of 36 and 42lcm of 9933.3cosx cosx 1 0derivative of e 4xdxdtax3 bx2 cx d1.3.83c and 5sx2-2x-15 0


text:
Previous issue ·  Next issue ·  Most recent issue · All issues

# Journal of Operator Theory

Volume 67, Issue 2, Spring 2012  pp. 437-467.

Proper actions of groupoids on $C^*$-algebras

Authors Jonathan Henry Brown
Author institution: Department of Mathematics and Statistics, University of Otago, P.O. Box 56, Dunedin 9054, New Zealand

Summary:  In 1990, Rieffel defined a notion of proper action of a group $H$ on a $C^*$-algebra $A$. He then defined a generalized fixed point algebra $A^{\alpha}$ for this action and showed that $A^{\alpha}$ is Morita equivalent to an ideal of the reduced crossed product. We generalize Rieffel's notion to define proper groupoid dynamical systems and show that the generalized fixed point algebra for proper groupoid actions is Morita equivalent to a subalgebra of the reduced crossed product. We give some nontrivial examples of proper groupoid dynamical systems and show that if $(\A, G, \alpha)$ is a groupoid dynamical system such that $G$ is principal and proper, then the action of $G$ on $\A$ is saturated, that is the generalized fixed point algebra is Morita equivalent to the reduced crossed product.

Contents    Full-Text PDF


text:
# Average Energy density and the Poynting vector of an EM wave

edfink1
Homework Statement:
Average Energy density and the Poynting vector of an EM wave
Relevant Equations:
energy density of the EM fields, Poynting vector
Hi,
In Problem 9.12 of Griffiths Introduction to Electrodynamics, 4th edition (Problem 9.11 3rd edition), in the problem, he says that one can calculate the average energy density and Poynting vector as

using the formula

I don't really understand how to do this. I show my attempt below, but I don't think it is good. Can someone explain if it is really all there is to it?

Delta2


text:
# Notation for differentiation

In differential calculus, there is no single uniform notation for differentiation. Instead, several different notations for the derivative of a function or variable have been proposed by different mathematicians. The usefulness of each notation varies with the context, and it is sometimes advantageous to use more than one notation in a given context. The most common notations for differentiation are listed below.

## Leibniz's notation

Main article: Leibniz's notation
dy
dx
d 2y
dx2

The original notation employed by Gottfried Leibniz is used throughout mathematics. It is particularly common when the equation y = f(x) is regarded as a functional relationship between dependent and independent variables y and x. In this case the derivative can be written as:

$\frac{dy}{dx}$

The function whose value at x is the derivative of f at x is therefore written

$\frac{d\bigl(f(x)\bigr)}{dx}\text{ or }\frac{d}{dx}\bigl(f(x)\bigr)$

(although strictly speaking this denotes the variable value of the derivative function rather than the derivative function itself).

Higher derivatives are expressed as

$\frac{d^ny}{dx^n},\quad\frac{d^n\bigl(f(x)\bigr)}{dx^n},\text{ or }\frac{d^n}{dx^n}\bigl(f(x)\bigr)$

for the nth derivative of y = f(x). Historically, this came from the fact that, for example, the third derivative is:

$\frac{d \Bigl(\frac{d \left( \frac{d y} {dx}\right)} {dx}\Bigr)} {dx} = \left(\frac{d}{dx}\right)^3 \bigl(f(x)\bigr)$

which we can loosely write (dropping the brackets in the denominator) as:

$\frac{d^3}{\left(dx\right)^3} \bigl(f(x)\bigr)=\frac{d^3}{dx^3} \bigl(f(x)\bigr)$

as above.

With Leibniz's notation, the value of the derivative of y at a point x = a can be written in two different ways:

$\frac{dy}{dx}\left.{\!\!\frac{}{}}\right|_{x=a} = \frac{dy}{dx}(a).$

Leibniz's notation allows one to specify the variable for differentiation (in the denominator). This is especially helpful when considering partial derivatives. It also makes the chain rule easy to remember and recognize:

$\frac{dy}{dx} = \frac{dy}{du} \cdot \frac{du}{dx}.$

In the formulation of calculus in terms of limits, the du symbol has been assigned various meanings by various authors.

Some authors do not assign a meaning to du by itself, but only as part of the symbol du/dx.

Others define dx as an independent variable, and use d(x + y) = dx + dy and d(x·y) = dx·y + x·dy as formal axioms for differentiation. See differential algebra.

In non-standard analysis du is defined as an infinitesimal.

It is also interpreted as the exterior derivative du of a function u.

## Lagrange's notation

f ʹ(x)  f ʺ(x)

One of the most common modern notations for differentiation is due to Joseph Louis Lagrange and uses the prime mark: the first three derivatives of f are denoted

$f'\;$ for the first derivative,
$f''\;$ for the second derivative,
$f'''\;$ for the third derivative.

After this, some authors continue by employing Roman numerals such as f IV for the fourth derivative of f, while others put the ordinal of the derivative in parentheses, so that the fourth derivative of f would be denoted f (4). The latter notation extends readily to any number of derivatives, so that the nth derivative of f is denoted f (n).

## Euler's notation

Dx y D2f

Euler's notation uses a differential operator, denoted as D, which is prefixed to the function so that the derivatives of a function f are denoted by

$Df \;$ for the first derivative,
$D^2f \;$ for the second derivative, and
$D^nf \;$ for the nth derivative, for any positive integer n.

When taking the derivative of a dependent variable y = f(x) it is common to add the independent variable x as a subscript to the D notation, leading to the alternative notation

$D_x y \;$ for the first derivative,
$D^2_x y\;$ for the second derivative, and
$D^n_x y \;$ for the nth derivative, for any positive integer n.

If there is only one independent variable present, the subscript to the operator is usually dropped, however.

Euler's notation is useful for stating and solving linear differential equations, as it simplifies presentation of the differential equation, which can make seeing the essential elements of the problem easier.

## Newton's notation

ẋ ẍ

Newton's notation for differentiation (also called the dot notation for differentiation) requires placing a dot over the dependent variable and is often used for time derivatives such as velocity

$\dot{y} = \frac{dy}{dt} \,,$

acceleration

$\ddot{y} = \frac{d^2y}{dt^2} \,,$

and so on. It can also be used as a direct substitute for the prime in Lagrange's notation. Again this is common for functions f(t) of time. Newton referred to this as a fluxion.[1]

Newton's notation is mainly used in mechanics, physics, and the theory of ordinary differential equations. It is usually only used for first and second derivatives, and then, only to denote derivatives with respect to time.

Dot notation is not very useful for higher-order derivatives, but in mechanics and other engineering fields, the use of higher than second-order derivatives is limited.

In physics, macroeconomics and other fields, Newton's notation is used mostly for time derivatives, as opposed to slope or position derivatives.

Newton did not develop a standard mathematical notation for integration but used many different notations.

## Partial derivatives

fx  fxy

When more specific types of differentiation are necessary, such as in multivariate calculus or tensor analysis, other notations are common.

For a function f(x), we can express the derivative using subscripts of the independent variable:

$f_x = \frac{df}{dx}$
$f_{x x} = \frac{d^2f}{dx^2}.$

This is especially useful for taking partial derivatives of a function of several variables.

∂f
∂x

Partial derivatives will generally be distinguished from ordinary derivatives by replacing the differential operator d with a "" symbol. For example, we can indicate the partial derivative of f(x,y,z) with respect to x, but not to y or z in several ways:

$\frac{\partial f}{\partial x} = f_x = \partial_x f = \partial^x f,$

where the final two notations are equivalent in flat Euclidean Space but are different in other manifolds.

Other notations can be found in various subfields of mathematics, physics, and engineering, see for example the Maxwell relations of thermodynamics. The symbol $\left(\frac{\partial T}{\partial V}\right)_S$ is the derivative of the temperature T with respect to the volume V while keeping constant the entropy S, while $\left(\frac{\partial T}{\partial V}\right)_P$ is the derivative of the temperature with respect to the volume while keeping constant the pressure P.

## Notation in vector calculus

Vector calculus concerns differentiation and integration of vector or scalar fields particularly in a three-dimensional Euclidean space, and uses specific notations of differentiation. In a Cartesian coordinate o-xyz, assuming a vector field A is $\mathbf{A} = (\mathbf{A}_x, \mathbf{A}_y, \mathbf{A}_z)$, and a scalar field $\varphi$ is $\varphi = f(x,y,z)\,$.

First, a differential operator, or a Hamilton operator which is called del is symbolically defined in the form of a vector,

$\nabla = \left( \frac{\partial}{\partial x}, \frac{\partial}{\partial y}, \frac{\partial}{\partial z} \right),$

where the terminology symbolically reflects that the operator ∇ will also be treated as an ordinary vector.

φ
• Gradient: The gradient $\mathrm{grad\,} \varphi\,$ of the scalar field $\varphi$ is a vector, which is symbolically expressed by the multiplication of ∇ and scalar field $\varphi$,
\begin{align} \operatorname{grad} \varphi &= \left( \frac{\partial \varphi}{\partial x}, \frac{\partial \varphi}{\partial y}, \frac{\partial \varphi}{\partial z} \right) \\ &= \left( \frac{\partial}{\partial x}, \frac{\partial}{\partial y}, \frac{\partial}{\partial z} \right) \varphi \\ &= \nabla \varphi \end{align}
∇∙A
• Divergence: The divergence $\mathrm{div}\,\mathbf{A}\,$ of the vector field A is a scalar, which is symbolically expressed by the dot product of ∇ and the vector A,
\begin{align} \operatorname{div} \mathbf{A} &= {\partial A_x \over \partial x} + {\partial A_y \over \partial y} + {\partial A_z \over \partial z} \\ &= \left( \frac{\partial}{\partial x}, \frac{\partial}{\partial y}, \frac{\partial}{\partial z} \right) \cdot \mathbf{A} \\ &= \nabla \cdot \mathbf{A} \end{align}
2φ
• Laplacian: The Laplacian $\operatorname{div} \operatorname{grad} \varphi$ of the scalar field $\varphi$ is a scalar, which is symbolically expressed by the scalar multiplication of ∇2 and the scalar field φ,
\begin{align} \operatorname{div} \operatorname{grad} \varphi &= \nabla \cdot (\nabla \varphi) \\ &= (\nabla \cdot \nabla) \varphi \\ &= \nabla^2 \varphi \\ &= \Delta \varphi \\ \end{align}
where, $\Delta = \nabla^2$ is called a Laplacian operator.
∇×A
• Rotation: The rotation $\mathrm{curl}\,\mathbf{A}\,$, or $\mathrm{rot}\,\mathbf{A}\,$, of the vector field A is a vector, which is symbolically expressed by the cross product of ∇ and the vector A,
\begin{align} \operatorname{curl} \mathbf{A} &= \left( {\partial A_z \over {\partial y} } - {\partial A_y \over {\partial z} }, {\partial A_x \over {\partial z} } - {\partial A_z \over {\partial x} }, {\partial A_y \over {\partial x} } - {\partial A_x \over {\partial y} } \right) \\ &= \left( {\partial A_z \over {\partial y} } - {\partial A_y \over {\partial z} } \right) \mathbf{i} + \left( {\partial A_x \over {\partial z} } - {\partial A_z \over {\partial x} } \right) \mathbf{j} + \left( {\partial A_y \over {\partial x} } - {\partial A_x \over {\partial y} } \right) \mathbf{k} \\ &= \begin{vmatrix} \mathbf{i} & \mathbf{j} & \mathbf{k} \\[5pt] \cfrac{\partial}{\partial x} & \cfrac{\partial}{\partial y} & \cfrac{\partial}{\partial z} \\[12pt] A_x & A_y & A_z \end{vmatrix} \\ &= \nabla \times \mathbf{A} \end{align}

Many symbolic operations of derivatives can be generalized in a straightforward manner by the gradient operator in Cartesian coordinates. For example, the single-variable product rule has a direct analogue in the multiplication of scalar fields by applying the gradient operator, as in

$(f g)' = f' g+f g' ~~~ \Longrightarrow ~~~ \nabla(\phi \psi) = (\nabla \phi) \psi + \phi (\nabla \psi).$

Further notations have been developed for more exotic types of spaces. For calculations in Minkowski space, the D'Alembert operator, also called the D'Alembertian, wave operator, or box operator is represented as $\Box$, or as $\Delta$ when not in conflict with the symbol for the Laplacian.


text:
## May 06, 2006

### Matrix cheat-sheet

[Math_] Normal matrices, spectral theorem, decompositions etc.

In the discussion below:
Q,U,V: unitary matrices (QQ*=I)
S: a diagonal matrix
R: an upper triangular matrix
X: a square matrix

A = any mxn matrix
=> A = USV* (SVD decomposition)
=> A = QR (general QR-decomp with Q mxn unitary i.e. QQ*=I)

A = any nxn square matrix
=> A = QRQ* (Schur decomposition)
=> A = QR (QR decomposition)
??? What is the relation between the two?

A = diagonalizable square matrix
=> A = XSX* (Eigen or spectral decomposition)

A = normal matrix (i.e. AA* = A*A)
=> A = QSQ* (Eigenvectors orthogonal - Spectral Theorem)

subclasses of normal matrices:
A = hermitian (i.e. A*=A, means symmetric if real)
A = skew-hermitian (i.e. A*=-A, skew-symmetric if real)
A = unitary (i.e. AA*=I, orthogonal if real)

subclasses of hermitian matrices:
A = positive semidefinite (i.e. all eigenvalues nonnegative)
=> SVD and eigen decompositions are the same: singular values need to be non-negative.
A = positive definite (i.e. all eigenvalues positive)

(1) Excerpt from http://en.wikipedia.org/wiki/Spectral_decomposition

These results translate immediately into results about matrices: For any normal matrix A, there exists a unitary matrix U such that

A=U \Lambda U*

where \Lambda is the diagonal matrix the entries of which are the eigenvalues of A. Furthermore, any matrix which can be diagonalized in this way must be normal.

The column vectors of U are the eigenvectors of A and they are orthogonal.

The spectral decomposition is a special case of the Schur decomposition. It is also a special case of the singular value decomposition.

If A is a real symmetric matrix, it follows by the real version of the spectral theorem for symmetric operators that there is an orthogonal matrix U such that UAU* is diagonal and all the eigenvalues of A are real.

(2) Excerpt from http://en.wikipedia.org/wiki/Eigenvalue%2C_eigenvector_and_eigenspace#Eigenvalue_equation

Decomposition theorems for general matrices

The decomposition theorem is a version of the spectral theorem in the particular case of matrices. This theorem is usually introduced in terms of coordinate transformation. If U is an invertible matrix, it can be seen as a transformation from one coordinate system to another, with the columns of U being the components of the new basis vectors within the old basis set. In this new system the coordinates of the vector v are labeled v'. The latter are obtained from the coordinates v in the original coordinate system by the relation v' = Uv and, the other way around, we have v = U − 1v'. Applying successively v' = Uv, w' = Uw and U − 1U = I, to the relation Av = w defining the matrix multiplication provides A'v' = w' with A' = UAU − 1, the representation of A in the new basis. In this situation, the matrices A and A' are said to be similar.

The decomposition theorem states that, if one chooses as columns of U − 1 n linearly independent eigenvectors of A, the new matrix A' = UAU − 1 is diagonal and its diagonal elements are the eigenvalues of A. If this is possible the matrix A is diagonalizable. An example of non-diagonalizable matrix is given by the matrix A above. There are several generalizations of this decomposition which can cope with the non-diagonalizable case, suited for different purposes:

* the Schur triangular form states that any matrix is unitarily equivalent to an upper triangular one;
* the singular value decomposition, A = UΣV * where Σ is diagonal with U and V unitary matrices. The diagonal entries of A = UΣV * are nonnegative; they are called the singular values of A. This can be done for non-square matrices as well;
* the Jordan normal form, where A = XΛX − 1 where Λ is not diagonal but block-diagonal. The number and the sizes of the Jordan blocks are dictated by the geometric and algebraic multiplicities of the eigenvalues. The Jordan decomposition is a fundamental result. One might glean from it immediately that a square matrix is described completely by its eigenvalues, including multiplicity, up to similarity. This shows mathematically the important role played by eigenvalues in the study of matrices;
* as an immediate consequence of Jordan decomposition, any matrix A can be written uniquely as A = S + N where S is diagonalizable, N is nilpotent (i.e., such that Nq=0 for some q), and S commutes with N (SN=NS).

Related link

#### 2 comments:

Anonymous said...

very helpful. thanks

bumbu pecel bali said...

this is good post, i like this....

form
http://bantalsilikon01.blogspot.com
http://bantalsilikon01.blogdetik.com

tanks very much.... :)


text:
Let's talk about insider trading. In an imaginary world where you know with certainty that the price of a stock will change on a given date - you can place a huge investment for enormous gains.

Why wouldn't you? There is no risk of the trade going bad because you have complete certainty in your buy (or sell) signal.

In the real world, an obvious downside is that this is illegal (unless you're in Congress), but the point remains - the size of your investment should scale with your confidence.

What do you do when you're in a similar spot while trading?

If you have a good system in place, you can increase (or decrease) your position size based on your level of confidence in the position, and do so without taking on a stupid amount of risk (like 99% of retail traders out there).

In fact, scaling your position size based on your level of conviction is a logical way to increase your returns - assuming you've done your backtesting homework, of course.

If the odds are in your favor, then you ought to increase your bet size accordingly. Of course, you shouldn't over bet - you could still be wrong no matter how high your conviction is - which would lead to a devastating loss.

So what kind of rules can we use?

Following up on a previous article, we explored adding multiple signals to our Starter System. By weighting them appropriately, we were able to combine them into a single, buy/sell signal.

Now, we're going to look at each of these components and determine how strong they are before combining them.

We'll call the signal strength our forecast for simplicity.

Including a forecast allows us to adjust our position based on how confident we are in the signal we're getting. Moreover, we'll also use it to adjust to the signal over time.

If risk is increasing, we should take some money off the table. Or if a trend is flattening out and signals are weakening, we can start getting out of our position before it completely reverses. Either of these can help cut down on your downside.

On the other hand, you might start with a small position due to a weak signal. But as more of your rules get on board and start screaming "Buy!" then your system will build a larger position.

This setup gives your system flexibility to adjust as the markets move through regimes.

Let's say we have a variety of Moving Average Crossover (MAC), Mean Breakout (MBO) and carry signals in our system. How do we determine the forecast for these?

The MAC's strength is determined by taking the difference between the fast moving average and the slow moving average and dividing this by our instrument risk. The larger the gap and lower the risk, the stronger your forecast.

In psuedo-code, we have:

F_mac[t] = SMA(fast, t) - SMA(slow, t) / STD(t)
Or, with mathematical notation: $$SMA_t^N = \frac{1}{N}\sum_{i=1}^N P_i$$ $$F_{MAC}^{f/s} = \frac{SMA_t^{fast} - SMA_t^{slow}}{\sigma}$$ Scaling the MAC by the risk is important for a few reasons.

For one, scaling the value helps standardize the signal when we're comparing it to the other rules in our system. Another reason is due to the wide range of prices we can see. If you have two instruments, both with a 1% difference in your moving averages, but the first is at $1,000 and the second is at$10, then the un-adjusted forecast signal on the first is $10 while it's$0.10 on the second. Scaling by risk helps to keep things in balance so you aren't heavily biased towards the more expensive instruments just because they're expensive!

For the MBO and carry rules, things are even easier because these don't require any additional scaling. We can just use the values as they are (and you can find the details on them here so I don't have to paste chunks of old articles below).

### Forecast Scaling Factors

There's one more step (actually, I lied, two more steps) before we're ready to work with these forecast values.

1. Scale appropriately
2. Set min and max values

Scale appropriately? Didn't we already do that when we adjusted the risk for the MAC?

Yes and no.

That was one very important type of scaling. There's a second adjustment that needs to be made for each of these values, they need to be scaled to keep their average value around 1.

This ensures that your different forecasts are all comparable to one another. If you have one forecast value that runs up to 40 and another at 2, then the second won't have much of an impact on your system.

Even within the same rule you can run into issues because the variations operate at different time scales.

Take a look at the forecasts for Tesla below:

These are all risk-adjusted, but don't have that second scaling factor. The long-term rules can really dominate simply because the slower the SMA, the larger the lag and larger the gaps can grow. You can see that the magnitude of changes is highly influenced by the time scale.

To get around these, Carver introduces scaling factors for each forecast variation.* Below, we show the scaling factors used in our system, taken from chapter 10 of Leveraged Trading:

*If you get the book, you'll see Carver's values are all 10X higher. He has a random scaling factor so that everything is 10X greater, then divides by 10 at the end because he likes 10. Well I like 1. It's arbitrary and makes no difference except now I can drop some zeros and don't have to divide by 10 in my code.

I'll be honest. I don't know exactly where Carver got these numbers from. He says it's from backtesting 37 different instruments and a whole bunch of synthetic data and should work for any market using these rules. That's about all the info I've got. I could try to reverse engineer it myself, but I'd rather spend my time elsewhere. So let's accept these values as Gospel and move on (for now).

Our code changes slightly for each of these rules. Here's the update for the MAC:

def _calcMAC(self, fast, slow, scale):
name = f'MAC{self.n_sigs}'
if f'SMA{fast}' not in self.data.columns:
self.data[f'SMA{fast}'] = self.data['Close'].rolling(fast).mean()
if f'SMA{slow}' not in self.data.columns:
self.data[f'SMA{slow}'] = self.data['Close'].rolling(slow).mean()
sig = self.data[f'SMA{fast}'] - self.data[f'SMA{slow}']
sig = sig.ffill().fillna(0) / self.data['risk_units'] * scale
self._clipForecast(sig, name)

Now, our final step is to constrain our forecast by our min/max values (last line in the code above). We're going to use +/- 2 for this.

We'll set up a new method to handle this:

def _clipForecast(self, signal, name):
sig = np.where(signal > self.max_forecast, self.max_forecast, signal)
sig = np.where(sig < self.min_forecast, self.min_forecast, sig)
self.data[name] = sig
self.signal_names.append(name)

MBO and carry follow the exact same pattern, just multiply by the scaling factor and clip it if it is outside of +/- 2.

Finally, we can calculate our forecast. For this we take the forecast of each variant and multiply it by the weights we used in our previous article.

## Forecast Example

Let's say we have all the weights and signals in the image above, and we've got these values to work with today:

Let's calculate the signal from the forecast!

First, we'll do an example MAC value. $$F_{MAC}^{8/32} = \bigg(\frac{9.89 - 9.97}{0.44}\bigg)(8.384) = -1.52$$ This is within +/- 2, so we leave it as is. The other values are outside of the range, so they get rounded to -2:

For the MBO values, we just multiply them by their appropriate scaling factor.

$$F_{MBO}^{20} = -0.37 \times 3.16 = -1.17$$

This, and all the MBO values, are greater than -2, so they don't get rounded.

The carry value just gets multiplied by its scaling factor of 3.

$$F_{CAR} = 0.64 \times 3 = 1.92$$

Finally, we get our signal by multiplying and summing the values of our rules and the weights.

Our weighted signal comes out to be 0.116, which means we're mildly long on this one because we're just over 0.

We want to take a position based on the strength of our signal, so we scale our target exposure accordingly.

$$s^T = \frac{r^T C \gamma}{\sigma}$$ where $$s^T$$ is our target exposure in dollars, $$r^T$$ is our target risk (12% for our default system), $$C$$ is our total capital, $$\sigma$$ is our instrument risk, and [latex]\gamma\) is our signal.

To make this concrete, if we have $1,000 to invest with a target risk of 12%, our signal at 0.116, and instrument risk of 16%, then we'd be looking to have$87 invested at this time. Compare that with the non-scaled value of $750 (just exclude the signal) and you see how we reduce our bet size to reflect our lack of conviction in the trade. Conversely, a high-signal trade (max of 2, remember?) would have us doubling our average exposure from$750 to $1,500! In other words, our system would be so confident in it that it would lever up in order to hit its target. What to do when the Winds Change? What do you do when your forecast changes or your risk decreases? In the previous systems, we did nothing - we were long or short with a static position. That makes trading simple, but not necessarily effective. Now, we'll use our forecast to dynamically re-adjust our position size by comparing our current exposure with the target exposure. Let's take the example from above, we have an initial target exposure of$87 and our stock is trading at $7 per share, so we buy 12 shares for an actual exposure of$84. Because of rounding, we're a little below our target, which is fine.

Some time passes and our new price is $8.50 and our forecast increases from a paltry 0.116 to 1.5 as more signals jump on board and go long. With the quick increase in price, we also saw a rise in the risk to 20%. We can recalculate our target and current exposure: $$s^T = \frac{0.12 \times (\8.50 \times 12 + \916) \times 1.5}{0.2} = \916.20$$ $$s^C = \8.50 \times 12 = \114$$ We're way off our target! Our current exposure is only$114, about 1/8th of what we should have, so we'll set our system to buy the 95 shares we need to get up to our new target, reflecting the higher confidence we have in our position.

We do need to be careful to avoid over trading. If we adjust our position too frequently, then we'll incur trading costs via transactions or the spread and erode our profits. Our exposure and target exposure change every day, so to prevent over trading, we're going to look at our exposure drift. This is a metric calculated by the difference between our target and current exposure, divided by our average exposure. If this is greater than a threshold (e.g. 10%), then we trade to bring our exposure back in line with the target.

What's our average exposure then?

Recall that our scaling factor was devised to set our signal to 1 on average. With that in mind, our average exposure is the exact same as our target exposure, except we set our forecast signal to 1. Easy.

$$s^{avg} = \frac{r^T C \gamma^{avg}}{\sigma}$$ Using the values in our example above, our average exposure comes out to \$610.80.
The exposure drift is then: $$\Delta s = \frac{s^T - s^C}{s^{avg}}$$ In our example case, our drift blew out to a huge 131%! In our actual system, we'd be rebalancing more frequently so that we shouldn't encounter such a drastic change - although it can happen in response to large price moves.

## Implementing the Forecast Algo

There aren't too many changes with the code versus the system developed in the last post in this series. We have a few new parameters, a slight modification to our signal calculation, and our rebalancing strategy via the exposure drift. The full code is available here:

class ForecastStarterSystem(ContinuousStarterSystem):
'''
Carver's Starter System without stop losses, multiple entry rules, and
a forecast for position sizing and rebalancing.

ContinuousStarterSystem class defined here:
https://gist.github.com/raposatech/49ccc66f5c312f939f8826251c55a676
'''
def __init__(self, ticker: str, signals: dict, target_risk: float = 0.12,
starting_capital: float = 1000, margin_cost: float = 0.04,
short_cost: float = 0.001, interest_on_balance: float = 0.0,
start: str = '2000-01-01', end: str = '2020-12-31',
shorts: bool = True, weights: list = [],
max_forecast: float = 2, min_forecast: float = -2,
exposure_drift: float = 0.1,
*args, **kwargs):

self.max_forecast = max_forecast
self.min_forecast = min_forecast
self.exposure_drift = exposure_drift

super().__init__(
ticker=ticker, signals=signals, target_risk=target_risk,
margin_cost=margin_cost, short_cost=short_cost, start=start,
end=end, interest_on_balance=interest_on_balance,
starting_capital=starting_capital, shorts=shorts,
weights=weights)

self._calcTotalSignal()

def _clipForecast(self, signal, name):
sig = np.where(signal > self.max_forecast, self.max_forecast, signal)
sig = np.where(sig < self.min_forecast, self.min_forecast, sig)
self.data[name] = sig
self.signal_names.append(name)

def _calcMAC(self, fast, slow, scale):
name = f'MAC{self.n_sigs}'
if f'SMA{fast}' not in self.data.columns:
self.data[f'SMA{fast}'] = self.data['Close'].rolling(fast).mean()
if f'SMA{slow}' not in self.data.columns:
self.data[f'SMA{slow}'] = self.data['Close'].rolling(slow).mean()
sig = self.data[f'SMA{fast}'] - self.data[f'SMA{slow}']
sig = sig.ffill().fillna(0) / self.data['risk_units'] * scale
self._clipForecast(sig, name)

def _calcMBO(self, periods, scale):
name = f'MBO{self.n_sigs}'
ul = self.data['Close'].rolling(periods).max()
ll = self.data['Close'].rolling(periods).min()
mean = self.data['Close'].rolling(periods).mean()
self.data[f'SPrice{periods}'] = (self.data['Close'] - mean) / (ul - ll)
sig = self.data[f'SPrice{periods}'].ffill().fillna(0) * scale
self._clipForecast(sig, name)

def _calcCarry(self, scale):
name = f'Carry{self.n_sigs}'
ttm_div = self.data['Dividends'].rolling(252).sum()
div_yield = ttm_div / self.data['Close']
net_long = div_yield - self.margin_cost
net_short = self.interest_on_balance - self.short_cost - ttm_div
self.data['net_return'] = (net_long - net_short) / 2
sig = self.data['net_return'] / self.data['STD'] * scale
self._clipForecast(sig, name)

def _calcSignals(self):
self.data['STD'] = self.data['Close'].pct_change().rolling(252).std() \
* np.sqrt(252)
self.data['risk_units'] = self.data['STD'] * self.data['Close']
self.n_sigs = 0
for k, v in self.signals.items():
if k == 'MAC':
for v1 in v.values():
self._calcMAC(v1['fast'], v1['slow'], v1['scale'])
self.n_sigs += 1

elif k == 'MBO':
for v1 in v.values():
self._calcMBO(v1['N'], v1['scale'])
self.n_sigs += 1

elif k == 'CAR':
for v1 in v.values():
if v1['status']:
self._calcCarry(v1['scale'])
self.n_sigs += 1

def _calcTotalSignal(self):
self.data['signal'] = self.data.apply(lambda x:
np.dot(x[self.signal_names].values, self.signal_weights),
axis=1)

def _sizePosition(self, capital, price, instrument_risk, signal):
exposure = self.target_risk * capital * \
np.abs(signal) / instrument_risk
shares = np.floor(exposure / price)
if shares * price > capital:
return np.floor(capital / price)
return shares

def _getExposureDrift(self, cash, position, price, signal,
instrument_risk):
if position == 0:
return 0, 0
capital = cash + price * position
exposure = self.target_risk * capital * signal / instrument_risk
cur_exposure = price * position
avg_exposure = self.target_risk * capital / instrument_risk * \
np.sign(signal)
return (exposure - cur_exposure) / avg_exposure, avg_exposure

def run(self):
position = np.zeros(self.data.shape[0])
rebalance = position.copy()
exp_delta = position.copy()
cash = position.copy()
for i, (ts, row) in enumerate(self.data.iterrows()):
if any(np.isnan(row.values)):
cash[i] = self._calcCash(cash[i-1], position[i],
row['Close'], row['Dividends']) if i > 0 \
else self.starting_capital
continue

# Propagate values forward
position[i] = position[i-1]
cash[i] = self._calcCash(cash[i-1], position[i],
row['Close'], row['Dividends'])

if row['signal'] > 0:
if position[i] <= 0:
cash[i] += position[i] * row['Close']
position[i] = self._sizePosition(
cash[i], row['Close'], row['STD'],
row['signal'])
cash[i] -= position[i] * row['Close']
# continue
elif row['signal'] < 0:
if position[i] >= 0:
cash[i] += position[i] * row['Close']
if self.shorts:
position[i] = -self._sizePosition(
cash[i], row['Close'], row['STD'],
row['signal'])
cash[i] -= position[i] * row['Close']
# continue
else:
position[i] = 0
else:
# Remain neutral if signal == 0
cash[i] += position[i] * row['Close']
position[i] = 0

# Check for rebalancing
delta_exposure, avg_exposure = self._getExposureDrift(
cash[i], position[i], row['Close'], row['signal'],
row['STD'])
exp_delta[i] += delta_exposure
if np.abs(delta_exposure) >= self.exposure_drift:
shares = np.round(delta_exposure * avg_exposure /
row['Close'])
cash[i] -= shares * row['Close']
position[i] += shares
rebalance[i] += shares

self.data['position'] = position
self.data['cash'] = cash
self.data['portfolio'] = self.data['position'] * \
self.data['Close'] + self.data['cash']
self.data['rebalance'] = rebalance
self.data['exposure_drift'] = exp_delta
self.data = calcReturns(self.data)

We inherit from our old model, add a few new parameters such as our min/max forecast and our exposure drift trigger, then initialize it and we're set. There are a few changes to some of the methods to take the scale factor into account and the signal dictionary structure changed slightly as well to include your custom scales (in case you want to change it).

sig_dict_carry = {
'MAC' : {
0: {'fast': 8, 'slow': 32, 'scale': 8.384},
1: {'fast': 16, 'slow': 64, 'scale': 5.712},
2: {'fast': 32, 'slow': 128, 'scale': 3.824},
3: {'fast': 64, 'slow': 256, 'scale': 2.528}
},
'MBO': {
0: {'N': 20, 'scale': 3.16},
1: {'N': 40, 'scale': 3.27},
2: {'N': 80, 'scale': 3.35},
3: {'N': 160, 'scale': 3.35},
4: {'N': 320, 'scale': 3.35}
},
'CAR': {
0: {'status': True, 'scale': 3}
}
}

We initialize and run this just like the other systems:

sys_fcast = ForecastStarterSystem(ticker='HAL', signals=sig_dict)
sys_fcast.run()

Viewing the stats:

fcast_stats = getStratStats(sys_fcast.data['strat_log_returns'])
bh_stats = getStratStats(sys_fcast.data['log_returns'])
stats = pd.DataFrame([fcast_stats, bh_stats],
stats

Looking at the equity curves, we see that the system is much more conservative, but out performs the underlying security over the long run.

We can also take a look at how the signal evolves over time and compare this to our continuous system without the forecast.

You can see that the forecast allows the system to take on larger positions both to the upside and downside. Although the continuous system's signal can range freely between -1 and 1, in practice, we round it up or down, which is why you see these large jumps in position in the second plot.

The forecast system really stands out in the second case during the COVID crash of 2020 where it went from a long position to being short, and then piled into that short position very quickly.

Let's zoom in on this region to better understand what's happening.

We're short HAL as its price is collapsing (bottom right plot). So our total capital is growing very quickly which bumps up the numerator in our target exposure. At the same time, the forecast is becoming stronger and stronger which is telling us we're more and more confident in this short. Finally, our actual exposure is decreasing because the price is falling.

All of this combines to lead to a rapid change in our exposure drift dictating that our system go short very quickly (risk is increasing too, but because that's on a rolling 12-month horizon, it moves much more slowly than these other values).

There is a big snap back in late March which results in our exposure drift blowing out to over 100% to the downside, meaning our position is now too large and we need to move the other way. You can see this in the top right plot in the day where the system closed out 80 shares of its position.

This was caused by a 26% jump in the price of the stock in one day.

The strategy wound up losing 9% on that move alone, but performed well through a very turbulent, boosting our portfolio by 22%.

## Dynamic Trend Following

Adding our forecast lets our trend following system become more dynamic. We take bigger bets when it makes sense and adjust our position along the way.

This approach helps us avoid a lot of the big drawdowns that occur during trading so we can continue to grow and compound our position.

In the next post, we'll cover what Carver says provides the biggest boost to this system: diversification.

To stay up to date with the latest, subscribe, and check out our free demo here!


text:
⚠ This EIP is not recommended for general use or implementation as it is likely to change.

# EIP-2315: Simple Subroutines for the EVM Source

Author Greg Colvin, Martin Holst Swende, Brooklyn Zelenka https://ethereum-magicians.org/t/eip-2315-simple-subroutines-for-the-evm/3941 Draft Standards Track Core 2019-10-17 3540, 3670

## Abstract

This proposal introduces five opcodes to support simple subroutines and relative jumps: JUMPSUB, RETURNSUB, RJUMP, RJUMPI, and RJUMPV.

These provide a safe, complete, static control-flow facility that supports substantial reductions in the complexity and the gas costs of calling and optimizing simple subroutines – from %33 to as much as 52% savings in gas.

Valid contracts will not halt with an exception unless they run out of gas or overflow stack while making a recursive subroutine call.

## Motivation

The EVM does not provide subroutines as a primitive. Instead, calls can be synthesized by fetching and pushing the current program counter on the data stack and jumping to the subroutine address; returns can be synthesized by getting the return address to the top of the stack and jumping back to it. These conventions create unnecessary cost and complexity that is borne by the humans and programs writing, reading, and analyzing EVM code,

Facilities to directly support subroutines are provided by all but one of the real and virtual machines programmed by the lead author, including the Burroughs 5000, CDC 7600, IBM 360, DEC PDP 11 and VAX, Motorola 68000, a few generations of Intel silicon, Sun SPARC, UCSD p-Machine, Sun JVM, Wasm, and the sole exception – the EVM. In whatever form, these operations provide for

• capturing the current context of execution,
• transferring control to a new context, and
• returning to the original context
• after possible further transfers of control
• to some arbitrary depth.

The concept goes back to Turing, 1946:

We also wish to be able to arrange for the splitting up of operations into subsidiary operations. This should be done in such a way that once we have written down how an operation is done we can use it as a subsidiary to any other operation. … When we wish to start on a subsidiary operation we need only make a note of where we left off the major operation and then apply the first instruction of the subsidiary. When the subsidiary is over we look up the note and continue with the major operation. Each subsidiary operation can end with instructions for this recovery of the note. How is the burying and disinterring of the note to be done? There are of course many ways. One is to keep a list of these notes in one or more standard size delay lines, (1024) with the most recent last. The position of the most recent of these will be kept in a fixed TS, and this reference will be modified every time a subsidiary is started or finished…

We propose to follow Turing’s simple concept in our subroutine design, as specified below. And we propose to validate the safe use of facility, so that valid contracts will not halt with an exception unless they run out of gas or overflow stack while making a recursive subroutine call.

### Gas Cost Analysis

We show here how these opcodes can be used to reduce the gas costs of both ordinary subroutine calls and low-level optimizations. The savings reported here will of course be less relevant to programs that use a few large subroutines rather than being a factored than into smaller ones. The choices of gas costs for the new opcodes below do not make a large difference in this analysis, as much of the improvement is due to PUSH and SWAP operations that are no longer needed. Even if JUMPSUB cost the same as JUMP – 8 gas rather than 5 - a simple subroutine call would still be 48% less costly versus 52%.

#### Simple Subroutine Call

Consider this example of calling a fairly minimal subroutine using JUMPSUB

Subroutine call, using JUMPSUB

TEST_SQUARE:
jumpdest        ; 1 gas
0x02            ; 3 gas
jumpsub SQUARE  ; 5 gas
returnsub       ; 3 gas

SQUARE:
jumpdest        ; 1 gas
dup1            ; 3 gas
mul             ; 5 gas
returnsub       ; 3 gas

Total 24 gas.

Subroutine call, using JUMP

TEST_SQUARE:
jumpdest        ; 1 gas
RTN_SQUARE      ; 3 gas
0x02            ; 3 gas
SQUARE          ; 3 gas
jump            ; 8 gas
RTN_SQUARE:
jumpdest        ; 1 gas
swap1           ; 3 gas
jump            ; 8 gas

SQUARE:
jumpdest        ; 1 gas
dup1            ; 3 gas
mul             ; 5 gas
swap1           ; 3 gas
jump            ; 8 gas

Total: 50 gas

Using JUMPSUB saves 50 - 24 = 26 gas versus using JUMP – a 52% performance improvement.

#### Tail Call Optimization

Of course in cases like this one we can optimize the tail call, so that the return from SQUARE actually returns from TEST_SQUARE.

Tail call optimization, using RJUMP and RETURNSUB.

TEST_SQUARE:
jumpdest        ; 1 gas
0x02            ; 3 gas
rjump SQUARE    ; 3 gas

SQUARE:
jumpdest        ; 1 gas
dup1            ; 3 gas
mul             ; 5 gas
returnsub       ; 3 gas

Total: 19 gas

Tail call optimization, using JUMP

TEST_SQUARE:
jumpdest        ; 1 gas
0x02            ; 3 gas
SQUARE          ; 3 gas
jump            ; 8 gas

SQUARE:
jumpdest        ; 1 gas
dup1            ; 3 gas
mul             ; 5 gas
swap1           ; 3 gas
jump            ; 8 gas

Total: 33 gas

Using JUMPSUB versus JUMP saves 33 - 19 = 14 gas – a 42% performance improvement.

So we can see that these instructions provide a simpler and more efficient subroutine mechanism than dynamic jumps.

#### Tail Call Elimination

We can even take advantage of SQUARE just happening to directly follow TEST_SQUARE and just fall through rather than jump at all.

Tail call elimination, using JUMPSUB.

TEST_SQUARE:
jumpdest        ; 1 gas
0x02            ; 3 gas
SQUARE:
jumpdest        ; 1 gas
dup1            ; 3 gas
mul             ; 5 gas
returnsub       ; 3 gas

Total 16 gas.

Tail call elimination, using JUMP.

TEST_SQUARE:
jumpdest        ; 1 gas
0x02            ; 3 gas
SQUARE:
jumpdest        ; 1 gas
dup1            ; 3 gas
mul             ; 5 gas
swap1           ; 3 gas
jump            ; 8 gas

Total: 24 gas

Using RETURNSUB versus JUMP saves 24 - 16 = 8 gas – a 33% performance improvement.

We can also consider the alternative subroutine call, using a version of JUMPSUB that pushes its return address on the stack.

TEST_SQUARE:
jumpdest        ; 1 gas
0x02            ; 3 gas
jumpsub SQUARE  ; 5 gas
swap1           ; 3 gas
returnsub       ; 3 gas

SQUARE:
jumpdest        ; 1 gas
dup1            ; 3 gas
mul             ; 5 gas
swap1           ; 3 gas
returnsub       ; 3 gas

Total 31 gas, compared to 24 gas for the return stack version.

## Specification

We introduce one more stack into the EVM in addition to the existing data stack, which we call the return stack. The return stack is limited to 1024 items. This stack supports three new instructions for subroutines.

### Instructions

#### JUMPSUB (0x5e) location

Transfers control to a subroutine.

1. Decode the location from the immediate data. The data is encoded as three bytes, MSB-first.
2. Set PC to location.

The cost is low.

• pops one item off the data stack
• pushes one item on the return stack

#### RETURNSUB (0x5f)

Returns control to the caller of a subroutine.

1. Pop PC off the return stack.

The cost is verylow.

• pops one item off the return stack

To provide a complete set of control structures, and to take full advantage of the performance benefits of simple subroutines we also provide two static, relative jump functions that take their arguments as immediate data rather then off the stack.

#### RJUMP (0x5c) offset

Transfers control to the address PC + offset, where offset is a two-byte, MSB first, twos-complement integer.

1. Decode the offset from the immediate data. The data is encoded as a two-byte, MSB first, twos-complement integer.
2. Set PC to location.

The cost is low.

#### RJUMPI (0x5d) offset

Conditionally transfers control to the address PC + offset, where offset is a two byte, MSB first, twos-complement integer.

1. Decode the offset from the immediate data. The data is encoded as a two-byte, MSB first, twos-complement integer.
2. Pop the condition from the stack.
3. If the condition is true then continue
4. Set PC to PC + offset.

The cost is mid.

#### RJUMPV (0x5e) n offset ...

Transfers control to the address at SP[0] + PC + 2 + offset; or else to the default address, where n and offset are two-byte, MSB first, twos-complement integers.

1. Pop n from the stack.
2. Decode the count from the immediate data. The data is encoded as two-byte, MSB first, twos-complement.
3. if (n < count) PC = PC[2 + 2*n] else PC = PC[2 + 2*count].

The cost is high.

Notes:

• If a resulting PC to be executed is beyond the last instruction then the opcode is implicitly a STOP, which is not an error.
• Values popped off the return stack do not need to be validated, since they are alterable only by JUMPSUB and RETURNSUB.
• The description above lays out the semantics of this feature in terms of a return stack. But the actual state of the return stack is not observable by EVM code or consensus-critical to the protocol. (For example, a node implementer may code JUMPSUB to unobservably push PC on the return stack rather than PC + 1, which is allowed so long as RETURNSUB observably returns control to the PC + 1 location.)
• The return stack is the functional equivalent of Turing’s “delay line”.

JUMP and JUMPI are assigned mid and high gas fees, and they require operations on 256-bit stack items and checking for valid destinations Whereas none of these operations require checking, and only RJUMPI requires 256-bit arithmetic. The low cost of JUMPSUB versus is justified by needing only to push the return address on the return stack and decode the immediate two byte destination to the PC, and the verylow cost of RETURNSUB is justified by needing only to pop the return stack into the PC. The low cost of RJUMP is justified by needing even less work than JUMPSUB, and the cost of RJUMPI is mid because of the extra work to test the conditional. RJUMPV is at least as costly as RJUMPI, with extra work for each offset. Benchmarking will be needed to tell if the costs are well-balanced.

### Validity

We define safety here as avoiding exceptional halting states:

• Valid contracts will not halt with an exception unless they
• run out of gas or
• overflow stack while making a recursive subroutine call.

Attempts to create contracts that cannot be proven to be valid will fail.

#### Exceptional Halting States

Execution is as defined in the Yellow Paper a sequence of changes to the EVM state. The conditions on valid code are preserved by state changes. At runtime, if execution of an instruction would violate a condition the execution is in an exceptional halting state. The Yellow Paper defines five such states.

1. Insufficient gas
2. More than 1024 stack items
3. Insufficient stack items
4. Invalid jump destination
5. Invalid instruction

We would like to consider EVM code valid iff no execution of the program can lead to an exceptional halting state, but we must be able to validate code in linear time to avoid denial of service attacks. So in practice, we can only partially meet these requirements. Our validation rules do not consider the code’s data and computations, only its control flow and stack use. This means we will reject programs with any invalid code paths, even if those paths are not reachable at runtime.

### Validation Rules

This section extends the contact creation validation rules (as defined in EIP-3540 and EIP-3670.)

1. Deprecate or restrict JUMP and JUMPI.
2. Every RJUMP, RJUMPI, and RJUMPV addresses only valid JUMPDESTs.
3. The stack depth is
• always positive and
• the same on every path through an opcode.
4. The number of items on the data stack and on the return stack is at most 1024.

The Yellow Paper has the stack pointer (SP) pointing just past the top item on the data stack. We define the stack base (BP)as the element that the SP addressed at the entry to the current basic block, or 0 on program entry, and the stack depth as the number of stack elements between the current SP and the current BP.

Taken together, these rules allow for code to be validated by traversing the control-flow graph, following each edge only once.

Note that this specification is entirely semantic. It constrains only data usage and control flow and imposes no syntax on code beyond being a sequence of bytes to be executed.

## Rationale

This is a simple two-stack design – the data stack is supplemented with a return stack to support jumping to and returning from subroutines, as specified above, and as conceptualized by Turing. The return address (Turing’s “note”) is pushed onto the return stack (Turing’s “delay line”) when calling, and the ‘PC’ is popped off of the PC when returning.

The alternative design is to push the return address and the destination address on the data stack before jumping to the subroutine, and to later jump back to the return address on the stack in order to return. This is the current approach. It could be streamlined to some extent by having JUMPSUB push the return address for RETURNSUB to pop.

We prefer the separate return stack because it maintains a clear separation between data and flow of control. This ensures that the return address cannot be overwritten or mislaid. It also reduces costs by using fewer data stack slots and moving less data.

## Backwards Compatibility

These changes affect the semantics of existing EVM code. These changes are compatible with the restricted forms of JUMP and JUMPI specified by EIP-3779 – contracts following all of the rules given there and here will be valid.

## Test Cases

### Simple routine

This should jump into a subroutine, back out and stop.

Bytecode: 0x60045e005b5d (PUSH1 0x04, JUMPSUB, STOP, JUMPDEST, RETURNSUB)

Pc Op Cost Stack RStack
0 JUMPSUB 5 [] []
3 RETURNSUB 5 [] [0]
4 STOP 0 [] []

Output: 0x Consumed gas: 10

### Two levels of subroutines

This should execute fine, going into one two depths of subroutines

Bytecode: 0x6800000000000000000c5e005b60115e5d5b5d (PUSH9 0x00000000000000000c, JUMPSUB, STOP, JUMPDEST, PUSH1 0x11, JUMPSUB, RETURNSUB, JUMPDEST, RETURNSUB)

Pc Op Cost Stack RStack
0 JUMPSUB 5 [] []
3 JUMPSUB 5 [] [0]
4 RETURNSUB 5 [] [0,3]
5 RETURNSUB 5 [] [3]
6 STOP 0 [] []

Consumed gas: 20

### Failure 1: invalid jump

This should fail, since the given location is outside of the code-range. The code is the same as previous example, except that the pushed location is 0x01000000000000000c instead of 0x0c.

Bytecode: (PUSH9 0x01000000000000000c, JUMPSUB, 0x6801000000000000000c5e005b60115e5d5b5d, STOP, JUMPDEST, PUSH1 0x11, JUMPSUB, RETURNSUB, JUMPDEST, RETURNSUB)

Pc Op Cost Stack RStack
0 JUMPSUB 10 [18446744073709551628] []
Error: at pc=10, op=JUMPSUB: invalid jump destination

### Failure 2: shallow return stack

This should fail at first opcode, due to shallow return_stack

Bytecode: 0x5d5858 (RETURNSUB, PC, PC)

Pc Op Cost Stack RStack
0 RETURNSUB 5 [] []
Error: at pc=0, op=RETURNSUB: invalid retsub

### Subroutine at end of code

In this example. the JUMPSUB is on the last byte of code. When the subroutine returns, it should hit the ‘virtual stop’ after the bytecode, and not exit with error

Bytecode: 0x6005565b5d5b60035e (PUSH1 0x05, JUMP, JUMPDEST, RETURNSUB, JUMPDEST, PUSH1 0x03, JUMPSUB)

Pc Op Cost Stack RStack
0 PUSH1 3 [] []
2 JUMP 8 [5] []
5 JUMPDEST 1 [] []
6 JUMPSUB 5 [] []
2 RETURNSUB 5 [] [2]
7 STOP 0 [] []

Consumed gas: 30

## Reference Implementation

### Validation Algorithm

This section specifies an algorithm for checking the above the rules. Equivalent code must be run at creation time. We assume that the validation defined in EIP-3540 and EIP-3670 has already run, although in practice the algorithms can be merged.

The following is a pseudo-Go implementation of an algorithm for enforcing adherence to the above rules. This algorithm is a symbolic execution of the program that recursively traverses the bytecode, following its control flow and stack use and checking for violations of the rules above. It uses a stack to track the slots that hold PUSHed constants, from which it pops the destinations to validate during the analysis.

This algorithm runs in time equal to O(vertices + edges) in the program’s control-flow graph, where edges represent control flow and the vertices represent basic blocks – thus the algorithm takes time proportional to the size of the bytecode.

For simplicity’s sake we assume a few helper functions.

• advance_pc() advances the PC, skipping any immediate data.
• imm_data() returns immediate data for an instruction.J
• valid_jumpdest() checks that a jump destination is not in immediate data.
• remove_items() returns the number of items removed from the stack by an instruction
• add_items() returns the number of items added to the stack. Items are added as 0xFFFFFFFF. The PC, PUSH…, SWAP…, DUP…, JUMP, and JUMPI instructions are handled separately.  var code [code_len]byte var depth [code_len]unsigned var sp := 1023
var bp := 1023

func validate(pc := 0, depth := 0) boolean {

for ; pc < code_len; pc = advance_pc(pc) {

  // successful termination
switch instruction {
case STOP    { return true }
case RETURN  { return true }
case SUICIDE { return true }
}

// check for stack underflow and overflow
depth := bp - sp
if depth < 0 || sp < 0 || 1024 < sp {
return false
}

// if stack depth for pc is non-zero we have been here before
if depth[pc] != 0 {
if depth[pc] != depth {
return false
}
return true
}
depth[pc] = depth

if (instruction == RJUMP) {

// check for valid destination
jumpdest = pc + imm_data(pc)
if !valid_jumpdest(jumpdest) {
return false
}

// will enter basic block at destination
bp = sp

// reset pc to destination of jump
pc = jumpdest
continue
}
if (instruction == RJUMPV {

// check for valid destination
n = imm_data(pc += 2)
for i := 0; i < n; n-- {
jumpdest = pc + n + imm_data(pc)
if !valid_jumpdest(jumpdest) {
return false
}
if !validate(jumpdest) {
return false
}
}
// false side of conditional

// enter basic block
bp = sp
continue
}
if (instruction == JUMPDEST) {

// enter basic block
bp = sp
continue
}

// apply other instructions to stack
sp += remove_items(pc)

// successful termination return true }

## Security Considerations

These changes do introduce new flow control instructions, so any software which does static/dynamic analysis of EVM code needs to be modified accordingly. The JUMPSUB semantics are similar to JUMP whereas the RETURNSUB instruction is different, since it can ‘land’ on any opcode (but the possible destinations can be statically inferred).

The validation algorithm must run in time and space near-linear in the size of its input so that a it can be charged appropriate gas to avoid DoS attack. RJUMPV takes its arguments inline so that attempts to attack the validation algorithm will fail by reducing the space available to attack it in.

Copyright and related rights waived via CC0.


text:
The Coronae of F-K Dwarfs: Factors Controlling Their Properties
Session 38 -- EUVE -- Astronomy II
Oral presentation, Tuesday, 2:00-6:30, Zellerbach Auditorium Room

## [38.06] The Coronae of F-K Dwarfs: Factors Controlling Their Properties

C. Jordan (U. of Oxford)

X-ray observations of late-type stars can be used to determine average coronal emission measures, Em(T$_c$), and temperature, T$_c$, provided the spectra can be fitted adequately by single temperatures. Em(T$_c$) and T$_c$ can be correlated with stellar properties, such as the rotation period, or with convection zone parameters, such as the Rossby number (Ro = P(rot)/turnover time at the base of the convection zone). Including F to K dwarfs, the closest correlations are found between Em(T$_c$) g$\cdot ^{\frac{1}{2}}$ and Ro, and T$_c$ g$\cdot ^{\frac{1}{2}}$ and Ro. The total energy losses from the coronae (radiation plus thermal conduction) can, with some assumptions, also be expressed in terms of Em(T$_c$) and T$_c$. These total losses, and hence the non-thermal energy required to heat the corona, scale approximately as Ro$^{-1}$. The coronal magnetic field can also be expressed in terms of Em(T$_c$) and T$_c$, through the pressure and plasma Beta, and comparisons can be made with specific heating mechanisms. Some recent results will be presented, including the relation between these implied coronal fields and surface magnetic fields and filling factors. The contribution from new observations with ROSAT, and expected from EUVE, will be discussed.

This work has been supported by the SERC through grant GR/H25539.


text:
## Results (1-50 of at least 1000)

Next
Orbit label Conrey labels Modulus Conductor Order Parity Primitive
1.a $1$ $1$ $1$ even
3.b $3$ $3$ $2$ odd
4.b $4$ $4$ $2$ odd
5.b $5$ $5$ $2$ even
5.c $5$ $5$ $4$ odd
7.b $7$ $7$ $2$ odd
7.c $7$ $7$ $3$ even
7.d $7$ $7$ $6$ odd
8.b $8$ $8$ $2$ even
8.d $8$ $8$ $2$ odd
9.c $9$ $9$ $3$ even
9.d $9$ $9$ $6$ odd
11.b $11$ $11$ $2$ odd
11.c $11$ $11$ $5$ even
11.d $11$ $11$ $10$ odd
12.b $12$ $12$ $2$ even
13.b $13$ $13$ $2$ even
13.c $13$ $13$ $3$ even
13.d $13$ $13$ $4$ odd
13.e $13$ $13$ $6$ even
13.f $13$ $13$ $12$ odd
15.d $15$ $15$ $2$ odd
15.e $15$ $15$ $4$ even
16.e $16$ $16$ $4$ even
16.f $16$ $16$ $4$ odd
17.b $17$ $17$ $2$ even
17.c $17$ $17$ $4$ even
17.d $17$ $17$ $8$ even
17.e $17$ $17$ $16$ odd
19.b $19$ $19$ $2$ odd
19.c $19$ $19$ $3$ even
19.d $19$ $19$ $6$ odd
19.e $19$ $19$ $9$ even
19.f $19$ $19$ $18$ odd
20.d $20$ $20$ $2$ odd
20.e $20$ $20$ $4$ even
21.c $21$ $21$ $2$ even
21.g $21$ $21$ $6$ even
21.h $21$ $21$ $6$ odd
23.b $23$ $23$ $2$ odd
23.c $23$ $23$ $11$ even
23.d $23$ $23$ $22$ odd
24.f $24$ $24$ $2$ even
24.h $24$ $24$ $2$ odd
25.d $25$ $25$ $5$ even
25.e $25$ $25$ $10$ even
25.f $25$ $25$ $20$ odd
27.e $27$ $27$ $9$ even
27.f $27$ $27$ $18$ odd
28.d $28$ $28$ $2$ even
Next


text:
Author nanonyme nanonyme 2018-01-17.18:09:12 -1.0 Yes <1516212552.32.0.467229070634.issue32587@psf.upfronthosting.co.za>
Content
MSDN documents that REG_MULTI_SZ is not supposed to have \0\0 anywhere else than in the end. The comment in
https://github.com/python/cpython/blob/a5293b4ff2c1b5446947b4986f98ecf5d52432d4/PC/winreg.c#L504
clearly shows that Python has the assumption that this specification is actually correct. However, Microsoft is violating it eg in https://technet.microsoft.com/en-us/library/cc960241.aspx which prevents you from reading that registry key in Python at all. This is a list which is treated as pairs:
"""
foo

meep
bar
"""
so you can have empty items which in Windows semantics means "remove this file". This results in a string like "foo\0\0meep\0\bar\0\0". I'm proposing relaxing Python registry handling semantics because it's clearly Microsoft isn't following this either
History
Date User Action Args
2018-01-17 18:09:12nanonymesetrecipients: + nanonyme
2018-01-17 18:09:12nanonymesetmessageid: <1516212552.32.0.467229070634.issue32587@psf.upfronthosting.co.za>