text:
4.5
(100k+ )
1

### AIEEE 2012

Let $$a,b \in R$$ be such that the function $$f$$ given by $$f\left( x \right) = In\left| x \right| + b{x^2} + ax,\,x \ne 0$$ has extreme values at $$x=-1$$ and $$x=2$$

Statement-1 : $$f$$ has local maximum at $$x=-1$$ and at $$x=2$$.

Statement-2 : $$a = {1 \over 2}$$ and $$b = {-1 \over 4}$$

A
Statement - 1 is false, Statement - 2 is true.
B
Statement - 1 is true , Statement - 2 is true; Statement - 2 is a correct explanation for Statement - 1.
C
Statement - 1 is true, Statement - 2 is true; Statement - 2 is not a correct explanation for Statement - 1.
D
Statement - 1 is true, Statement - 2 is false.

## Explanation

Given, $$f\left( x \right) = \ln \left| x \right| + b{x^2} + ax$$

$$\therefore$$ $$f'\left( x \right) = {1 \over x} + 2bx + a$$

At $$x=-1,$$ $$f'\left( x \right) = - 1 - 2b + a = 0$$

$$\Rightarrow a - 2b = 1\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,...\left( i \right)$$

At $$x=2,$$ $$\,\,f'\left( x \right) = {1 \over 2} + 4b + a = 0$$

$$\Rightarrow a + 4b = - {1 \over 2}\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,...\left( {ii} \right)$$

On solving $$(i)$$ and $$(ii)$$ we get $$a = {1 \over 2},b = - {1 \over 4}$$

Thus, $$f'\left( x \right) = {1 \over x} - {x \over 2} + {1 \over 2} = {{2 - {x^2} + x} \over {2x}}$$

$$= {{ - {x^2} + x + 2} \over {2x}} = {{ - \left( {{x^2} - x - 2} \right)} \over {2x}} = {{ - \left( {x + 1} \right)\left( {x - 2} \right)} \over {2x}}$$

So maximum at $$x=-1,2$$

Hence both the statements are true and statement $$2$$ is a correct explanation for $$1.$$
2

### AIEEE 2012

A spherical balloon is filled with $$4500\pi$$ cubic meters of helium gas. If a leak in the balloon causes the gas to escape at the rate of $$72\pi$$ cubic meters per minute, then the rate (in meters per minute) at which the radius of the balloon decreases $$49$$ minutes after the leakage began is :
A
$${{9 \over 7}}$$
B
$${{7 \over 9}}$$
C
$${{2 \over 9}}$$
D
$${{9 \over 2}}$$

## Explanation

Volume of spherical balloon $$= V = {4 \over 3}\pi {r^3}$$

$$\Rightarrow 4500\pi = {{4\pi {r^3}} \over 3}$$

( as Given, volume $$= 4500\pi {m^3}$$ )

Differentiating both the sides, $$w.r.t't'$$ we get,

$${{dV} \over {dt}} = 4\pi {r^2}\left( {{{dr} \over {dt}}} \right)$$

Now, it is given that $${{dV} \over {dt}} = 72\pi$$

$$\therefore$$ After $$49$$ min, Volume -

$$\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, = \left( {4500 - 49 \times 72} \right)\pi$$

$$\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, = \left( {4500 - 3528} \right)\pi$$

$$\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, = 972\pi {m^3}$$

$$\Rightarrow V = 972\,\,\pi {m^3}$$

$$\therefore$$ $$972\pi = {4 \over 3}\pi r{}^3$$

$$\Rightarrow {r^3} = 3 \times 243 = 3 \times {3^5} = {3^6} = {\left( {{3^2}} \right)^3} \Rightarrow r = 9$$

Also, we have $${{dV} \over {dt}} = 72\pi$$

$$\therefore$$ $$72\pi = 4\pi \times 9 \times 9\left( {{{dr} \over {dt}}} \right) \Rightarrow {{dr} \over {dt}} = \left( {{2 \over 9}} \right)$$
3

### AIEEE 2011

The shortest distance between line $$y-x=1$$ and curve $$x = {y^2}$$ is
A
$${{3\sqrt 2 } \over 8}$$
B
$${8 \over {3\sqrt 2 }}$$
C
$${4 \over {\sqrt 3 }}$$
D
$${{\sqrt 3 } \over 4}$$

## Explanation

Shortest distance between two curve occurred along -

the common normal

Slope of normal to $${y^2} = x$$ at point

$$P\left( {{t^2},t} \right)$$ is $$-2t$$ and

slope of line $$y - x = 1$$ is $$1.$$

As they are perpendicular to each other

$$\therefore$$ $$\left( { - 2t} \right) = - 1 \Rightarrow t = {1 \over 2}$$

$$\therefore$$ $$P\left( {{1 \over 4},{1 \over 2}} \right)$$

and shortest distance $$= \left| {{{{1 \over 2} - {1 \over 4} - 1} \over {\sqrt 2 }}} \right|$$

So shortest distance between them is $${{3\sqrt 2 } \over 8}$$
4

### AIEEE 2011

For $$x \in \left( {0,{{5\pi } \over 2}} \right),$$ define $$f\left( x \right) = \int\limits_0^x {\sqrt t \sin t\,dt.}$$ Then $$f$$ has
A
local minimum at $$\pi$$ and $$2\pi$$
B
local minimum at $$\pi$$ and local maximum at $$2\pi$$
C
local maximum at $$\pi$$ and local minimum at $$2\pi$$
D
local maximum at $$\pi$$ and $$2\pi$$

## Explanation

$$f'\left( x \right) = \sqrt x \sin x$$

At local maxima or minima, $$f'\left( x \right) = 0$$

$$\Rightarrow x = 0$$ or $$sin$$ $$x=0$$

$$\Rightarrow x = 2\pi ,\,\,\pi \in \left( {0,{{5\pi } \over 2}} \right)$$

$$f''\left( x \right) = \sqrt x \cos \,x + {1 \over {2\sqrt x }}\sin \,x$$

$$= {1 \over {2\sqrt x }}\left( {2x\,\cos \,x + \sin \,x} \right)$$

At $$x = \pi ,$$ $$f''\left( x \right) < 0$$

Hence, local maxima at $$x = \pi$$

At $$x = 2\pi ,\,\,\,f''\left( x \right) > 0$$

Hence local minima at $$x = 2\pi$$

### Joint Entrance Examination

JEE Main JEE Advanced WB JEE

### Graduate Aptitude Test in Engineering

GATE CSE GATE ECE GATE EE GATE ME GATE CE GATE PI GATE IN

NEET

Class 12


text:
# Two-point tensor

Two-point tensors, or double vectors, are tensor-like quantities which transform as euclidean vectors with respect to each of their indices and are used in continuum mechanics to transform between reference ("material") and present ("configuration") coordinates.[1] Examples include the deformation gradient and the first Piola–Kirchhoff stress tensor.

As with many applications of tensors, Einstein summation notation is frequently used. To clarify this notation, capital indices are often used to indicate reference coordinates and lowercase for present coordinates. Thus, a two-point tensor will have one capital and one lower-case index; for example, AjM.

## Continuum mechanics

A conventional tensor can be viewed as a transformation of vectors in one coordinate system to other vectors in the same coordinate system. In contrast, a two-point tensor transforms vectors from one coordinate system to another. That is, a conventional tensor,

${\displaystyle \mathbf {Q} =Q_{pq}(\mathbf {e} _{p}\otimes \mathbf {e} _{q})}$,

actively transforms a vector u to a vector v such that

${\displaystyle \mathbf {v} =\mathbf {Q} \mathbf {u} }$

where v and u are measured in the same space and their coordinates representation is with respect to the same basis (denoted by the "e").

In contrast, a two-point tensor, G will be written as

${\displaystyle \mathbf {G} =G_{pq}(\mathbf {e} _{p}\otimes \mathbf {E} _{q})}$

and will transform a vector, U, in E system to a vector, v, in the e system as

${\displaystyle \mathbf {v} =\mathbf {GU} }$.

## The transformation law for two-point tensor

Suppose we have two coordinate systems one primed and another unprimed and a vectors' components transform between them as

${\displaystyle v'_{p}=Q_{pq}v_{q}}$.

For tensors suppose we then have

${\displaystyle T_{pq}(e_{p}\otimes e_{q})}$.

A tensor in the system ${\displaystyle e_{i}}$. In another system, let the same tensor be given by

${\displaystyle T'_{pq}(e'_{p}\otimes e'_{q})}$.

We can say

${\displaystyle T'_{ij}=Q_{ip}Q_{jr}T_{pr}}$.

Then

${\displaystyle T'=QTQ^{\mathsf {T}}}$

is the routine tensor transformation. But a two-point tensor between these systems is just

${\displaystyle F_{pq}(e'_{p}\otimes e_{q})}$

which transforms as

${\displaystyle F'=QF}$.

## The most mundane example of a two-point tensor

The most mundane example of a two-point tensor is the transformation tensor, the Q in the above discussion. Note that

${\displaystyle v'_{p}=Q_{pq}u_{q}}$.

Now, writing out in full,

${\displaystyle u=u_{q}e_{q}}$

and also

${\displaystyle v=v'_{p}e'_{p}}$.

This then requires Q to be of the form

${\displaystyle Q_{pq}(e'_{p}\otimes e_{q})}$.

By definition of tensor product,

${\displaystyle (e'_{p}\otimes e_{q})e_{q}=(e_{q}.e_{q})e'_{p}=3e'_{p}}$

(1)

So we can write

${\displaystyle u_{p}e_{p}=(Q_{pq}(e'_{p}\otimes e_{q}))(v_{q}e_{q})}$

Thus

${\displaystyle u_{p}e_{p}=Q_{pq}v_{q}(e'_{p}\otimes e_{q})e_{q}}$

Incorporating (1), we have

${\displaystyle u_{p}e_{p}=Q_{pq}v_{q}e_{p}}$.

In the equation following (1) there are four q's !?

format: plain


text:
• ### Popular Now

• 13
• 16
• 27
• 9
• 9

#### Archived

This topic is now archived and is closed to further replies.

# 04.09 - Game States and Variable Scope

This topic is 6080 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

From Demos to Games Throughout the last eight articles, we''ve taken a tour of different game elements, each an integral part of game development. Of course, what we''ve written thus far could hardly be considered games. But let''s face it -- you can''t write games unless you can display/animate images, control timing, understand resolutions and colors, and harness DirectX to make all of these work together. Now that we have some skill in these departments, what''s missing? Continuity. That''s what we''re missing. Games don''t just start with players running around and shooting. There''s intro screens, menus, multiple levels, intros/outros and cutscenes, etc. In other words, a game consists of many different components, and all we''ve got so far is our single entry point, Game_Main(). Obviously if we want to write anything robust, we''re going to need a little help. Life in Game_Main() We know that Game_Main() is executed continually, and the approach we''re taking is to render a single frame of animation each time. We also know that the only way to remind ourselves in Game_Main() of what we''re supposed to be doing each frame is by keeping track of everything with static/global variables and other data structures. All that we need to do is add an additional level of organization so that our game not only knows ''how'' to do things, but ''when'' to do things. As an example, say our game consists of an intro screen (something that says, "Press SPACE to begin"), and the actual game where our sprites are moving around, etc. We''d start by thinking of these two components as separate, and assign a new global variable to keep track of where the user is:

enum GameState {GS_INTRO, GS_GAME};

// Our G structure in GLOBALS.H
struct
{
...
GameState gameState;
...
} G;

Somewhere in Game_Initialize() we would initialize this variable like so:

G.gameState = GS_INTRO;

...and in Game_Main(), we could branch-off depending on the game state:

void Game_Main()
{
if (G.gameState == GS_INTRO)
{
// Show the intro screen
}
else
{
// The game -- move sprites
}
}

This is about the simplist mechanism for game states that I could think of. Of course, for this particular example it works fine, so there would be no need to go further. In reality though, we''ll have more than two game states, and this if/else structure could quickly become large and unweildy. How else could we implement this type of ''filter''? How about this:

void Game_Main()
{
switch (G.gameState)
{
case GS_INTRO: GS_Intro(); break;
case GS_GAME:  GS_Game();  break;
}
}

This approach definitely seems a lot smarter, as it calls a corresponding game function for each possible game state. And, let me tell you, you will not want to be writing entire games in Game_Main() unless they''re very small... Sometimes you might want to use a combination of the two -- a main game state that determines which function gets called, and a secondary, or sub-state variable to act as a filter once in the proper game function. Here''s an example of what I mean:

enum MainGS {MGS_INTRO, MGS_GAME};
enum SubGS  {SGS_MOVING, SGS_SHOOTING, SGS_DYING};

// Our G structure in GLOBALS.H
struct
{
...
MainGS gameState;
SubGS  gameSubState;
...
} G;

Here, we could use gameState to call the appropriate game function (e.g. using the switch construct), and we could use gameSubState from within the chosen game function as a helper. What you get is two levels of indirection that can help you better organize what code needs to be executed when in order for your game to work properly. Another technique involves using function pointers, which is a powerful programming technique that''s covered in Tricks and Techniques. Sufficive to say, we don''t need anything of these calibre for our immediate purposes. Tracing Your Footsteps The use of enumerated game states is definitely going to help us organize a simple game, and there''s one more game state that we should be keeping track of to make life a little easier on us. It turns out that it''s often important to know not only what state we''re currently in, but what state we''re coming from. To validate this need, take a look at the following:

...
{
// Code to animate player''s death
}
...

Let''s assume that the code for this block is responsible for an animation spanning multiple sprite frames controlled by a timer. You see, this block of code is going to be executed repeatedly because the game state GS_DEAD will be the current game state for the whole time the player is seen crouching over and dying, and this means that there will be variables that need to be initialized. One way to accomplish this is to add a little logic like so:

...
{
{
// Initialize local variables
// ...
}

// Code to animate player''s death
}
...

The first time this code is executed, it knows that it''s the first time and therefore can initialize any local variables it needs to render the player''s death properly. Once this code has completed the sequence, it will change the current game state to something other than GS_DEAD. The new game state can then in turn utilize this initialization technique as well. Of course, there are other ways to do this:

...
{
static bool bInit = FALSE;

if (bInit == FALSE)
{
// Initialize local variables
// ...
bInit = TRUE;
}

// Code to animate player''s death

// Are we done with this game state?
if (bDeathSequenceComplete == TRUE)
{
bInit = FALSE;
G.gameState = GS_SOMETHINGELSE;
}
}
...

Here we''re using a static variable, just like we did with Game_Main() in earlier articles. When this game state is complete, it''s important to reset the bInit flag so that later on in the game if GS_DEAD starts again, it will once again be initialized properly. Variable Scope When talking about game states, I alluded to the fact that large games need more than one main function. By the same token, large games should use more than one source code file for their game code as well. Luckily for us, our global G structure is designed so that any source file (module) can automatically ''see'' these global variables. All that you have to do is create a new source file and make sure this is the top:

#include "Globals.h"

You can then start writing functions inside of this new source file that work with your global variables, thereby contributing to the game. When working with multiple modules, it sometimes becomes important to further organize variables, as games can end up with a lot of them. Consider this example source file:

// EXAMPLE.CPP

#include "Globals.h"

static struct
{
int xpos, ypos;
int spriteState;
} L;

void Function1()
{
int local1;
// ...
}

void Function2()
{
bool bLocal;
// ...
}

Bacause of the #include at the top of the file, this file can freely make use of our G structure. At the top of this file is another structure called L, which stands for LOCAL, and holds some variables that only functions in this file can use. There are two reasons for grouping variables in this way:
• Using L gives us the look and feel of C++ classes, where all variables that belong to the module exist. If we combine all of the functions with a common purpose together with the variables they share, we have a clean and intuitive source code arrangement to work with.
• When reading the source code, one can easily distinguish which variables are local to the function, and which are also used by other functions in the module (i.e. there''s an ''L.'' before them).
Putting everything together, we get a template like this:

G
{
FILE1
{
L
{
Function1
{
local (stack) variables
}
Function2
{
local (stack) variables
}
...
}
}
FILE2
{
L
{
Function10
{
local (stack) variables
}
...
}
}
...
}

This illustration shows that G is visible by everything, and L is visible to the file in which it resides. In order to realize the benefits of this system of data organization, you have to be sure to properly organize your variables:
• If a variable is only needed by a single function, create it within the function
• If a variable is needed by more than one function,
1. if the functions seem like they belong to a group, group them to a file and place the variable in an L structure (i.e. file scope)
2. if the functions are in different files and shouldn''t be moved, place the variable in G

##### Share on other sites
I''m not trying to bother everyone by posting this here, but maybe since it''s at the top I''ll get a responce. My problem is that I don''t have VC++ or the money to buy it, although I do have Dev C++ and Borland 5.5. If you have used either of these to compile to sample project successfully please e-mail me and tell me how you did it. I hope to eventually get VC++, but at the moment I don''t have the money.

##### Share on other sites
Help!!!! Teej''s website with needed materials won''t pull up. It''s not just me because I tried it at work also. Anyone know what the deal is? Teej, if you see this then you, of course, would be able to provide the best answer. Hopefully you''ll check back today since this is a new topic. Any help at all would be accepted with open arms, though.

##### Share on other sites
The anonymous was me.

"Those who are skilled in combat do not become angered, those who are skilled at winning do not become afraid. Thus the wise win before they fight, while the ignorant fight to win."

##### Share on other sites
Anon,

I''ve got the same problem as you: I haven''t been able to pull up Teej''s website. I always get a "Page Not Found" screen. Like yourself, I need to get the source files off the site. I hope Teej fixes that link.

Carlos

##### Share on other sites
For those having trouble accessing his site, I believe Teej has moved to a new location:

http://www.angelfire.com/home/gamedev

Edited by - DTM on June 26, 2001 10:28:07 PM

##### Share on other sites
Thanks a lot! I''ve got the files now.

"Those who are skilled in combat do not become angered, those who are skilled at winning do not become afraid. Thus the wise win before they fight, while the ignorant fight to win."

##### Share on other sites
good job so far Teej. I really am enjoying playing around with the information I''ve gained through this tutorial along with a few other resources. I think you''re right about not starting out with a grandiose 3D project, though I think there is something to be said for finding your own methods and/or finding time-tested methods through your own hard work, patience and/or logic. Anyway, I just wanted to reiterate that you''re doing a great job.

##### Share on other sites
What is the deal with using non bmp files as our image files? I have a background (contains 296 colours) I would like to use for a program I am working on, and if I make a gif with it is around 150kbs, and if it is a bmp it is around 400 kbs, quite a difference really.

So are we really confined to using bmps or can we use any image files for our sources on DirectX.


text:
# Questions on the relation of the axis of a cone to its conic sections

(1) Does the axis of a cone pass through the foci of any its conic sections? Consider the image below:

Is the intersection of the axis of cone and the ellipse the same as the focus of the ellipse? Also for the parabola? If not, what is the significance of this point where the conic section intersects the axis of the cone? Does the diameter of the base of the cone pass through the focus of the hyperbola?

(2) It is easy to see that the axis of the cone passes through the center of the circle, and that a plane passing through the vertex of a double cone would pass through the center point of a hyperbola. But how does one compute the center of the ellipse from this picture?

(3) The center of a conic section is equidistant from its foci. One can think of a circle as having one focus at its center, where an ellipse's foci would coincide if its major and minor axes were equal in length. But a parabola also has one focus, so what is the "center" of a parabola?

I am guessing all of these have something to do with Dandelin spheres as described here, but not sure that this answers my questions or not.

• The Dandelin spheres answer question (1): a focus of a conic section is the point of tangency of its plane with one of those spheres. Clearly, the point on tangency lies on the cone axis if and only if the plane is perpendicular to that axis; therefore, the axis contains a focus in, and only in, the case of a circle. The axis point has some relation to the conic section, but not one as interesting or useful as a focus. (As for "Does the diameter of the base of the cone pass through the focus of the hyperbola?": note that the cone has no base. The thing extends, and expands, infinitely-far.) – Blue Jun 20 '15 at 10:54
• (3) is easy: A parabola has no center! :) – Blue Jun 20 '15 at 10:58
• @Blue, of course (3) has an obvious answer in practical terms. But what I mean is that as the plane moves from being perpendicular to the axis of the cone, its eccentricity increases along the way. As this happens the center point of the conic section moves from the intersection of the axis to a point further and further away. In the case when the eccentricity, $e$ is 1 (parabola), it seems then that this center is infinitely far from the vertex. On the other hand, for $e>1,$ (hyperbola) we have the center reappearing "on the other side" of the vertex. Does this make sense? – John Molokach Jun 20 '15 at 12:41
• This may help visualize what I'm talking about. desmos.com/calculator/numfnsamlu. – John Molokach Jun 20 '15 at 12:43
• It absolutely makes sense. This notion of points seeming to move "out to infinity and come back on the other side" is not uncommon in analytical geometry. (It's kinda what happens along asymptotes, when you think about it.) You might be interested in studying Projective Geometry, which adds a "line at infinity" to the standard Euclidean plane; this broader context helps unify all the conic sections into a single kind of curve that has various different relations to that line. (The parabola, in particular, has its "second vertex" on that line.) – Blue Jun 20 '15 at 12:48

The Dandelin spheres answer question (1): a focus of a conic section is the point of tangency of its plane with one of those spheres. Clearly, the point on tangency lies on the cone axis if and only if the plane is perpendicular to that axis; therefore, the axis contains a focus in, and only in, the case of a circle. The axis point has some relation to the conic section, but not one as interesting or useful as a focus. (As for "Does the diameter of the base of the cone pass through the focus of the hyperbola?": note that the cone has no base. The thing extends, and expands, infinitely-far.)

This notion of points seeming to move "out to infinity and come back on the other side" is not uncommon in analytical geometry. (It's kinda what happens along asymptotes, when you think about it.) You might be interested in studying Projective Geometry, which adds a "line at infinity" to the standard Euclidean plane; this broader context helps unify all the conic sections into a single kind of curve that has various different relations to that line. (The parabola, in particular, has its "second vertex" on that line.)

I have made some computations with the cone $C$ of equation $$z^2 = x^2 + y^2$$ and the plane $\Pi$ through the point $P = (0,0,1)$ generated by the vectors $v=(1,0,0)$ and $w=(0,\frac{4}{5},\frac{3}{5})$. Namely, $\Pi$ is given parametrically as $P + s v + t w$, where $s,t$ are the parameters.

So if your claim (1) is true then the point $P$ must be a foci of the intersection of $\Pi$ and $C$. I did all the computations and if I do not made mistakes this do not happen. Here are the computations:

Points of the plane are $(x,y,z) = (0,0,1) + s(1,0,0) + t(0,\frac{4}{5},\frac{3}{5}) = (s,t\frac{4}{5},1+t\frac{3}{5})$ for any $s,t \in \mathbb{R}$. So such a point is in the cone $C$ iff $$(1+t\frac{3}{5})^2 = s^2 + (t\frac{4}{5})^2$$ Now by completing the square the above equation becomes $$1 = \frac{s^2}{\frac{16}{7}} + \frac{(t - \frac{15}{7})^2}{(\frac{20}{7})^2}$$ showing that the conic section is a ellipse centered at the point $Q$ of $\Pi$ of coordinates $(s,t) = (0,\frac{15}{7})$ i.e. $Q = (0, \frac{12}{7},\frac{16}{7})$. The foci are the points whose coordinates $(s,t)$ are $(0,c)$ where $$c = \frac{15}{7} \pm \sqrt{ (\frac{20}{7})^2 - \frac{16}{7}} = \frac{15 \pm 12 \sqrt{2}}{7}$$ So no foci has coordinates $(0,0)$ showing that indeed the point $P$ is not a foci of the ellipse.

Conceptually, it seems to me that your question (1) should be equivalent to the claim that foci are invariant by projective transformatons of the conic. But this is not true as you can check by rescaling the axis $(x,y)$ of a ellipse $\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1$. The rescaling is the map $(x,y) \to (\alpha x, \beta y)$, where $\alpha,\beta > 0$ which is of course a projective map (but writen in affine coordinates $x,y$).

• Seems right. I am not exactly sure how to proceed with your calculation. Can you outline a first step or two? – John Molokach Jun 20 '15 at 12:49
• OK, I am going to edit my answer and add some steps to compute the foci of the conic I proposed. – Holonomia Jun 20 '15 at 13:14
• Your calculations seem right. This definitely sheds light on the question, but I think @Blue's remarks are more general, especially in light of the car of the parabola. – John Molokach Jun 20 '15 at 14:59
• I had forgotten of Dandelin spheres an it application to link the conic section to the ellipse defined by means of distance to foci, so I am happy to recall this. In any case the computation I did is not so important as the comment in my last paragraph that show that claim (1) is not true since 'foci' is not a concept that belong to the projective geometry of the conic. – Holonomia Jun 20 '15 at 15:59


text:
The TextField component

TextField components let the user enter text on a single line.

In addition to the properties listed below, this component inherits properties and methods from the superclass Component. For example, any TextField component has a label and defaultValue property even though these are not explicitly listed here.

Properties

NameDescriptionDatatypeDefault
labelPositionPosition of the label with respect to the textfield. Can be 'right', 'left', 'top' or 'bottom'.String'top'
multipleWhether or not multiple values can be entered.BooleanFalse


text:
# 2021级《程序设计原理及C语言》练习题

A. Max, Min and Avg

Input several one blank separated integers, output the maximum, minimum and average (with %.2f format) of all positive integers separated by a space in one line and those of all negative integers in next line.

### 输入格式

There are no more than $10^6$ integers. Every one of them can be stored in a signed 32-bit integer. It is guaranteed that there is at least one positive integer and at least one negative integer.

### 样例

Input
-1 -2 -3 -4 -5 -6 1 2 3 4
Output
4.00 1.00 2.50
-1.00 -6.00 -3.50

NaN


text:
zbMATH — the first resource for mathematics

New exact algorithms for the 2-constraint satisfaction problem. (English) Zbl 1290.68144
Summary: Many optimization problems can be phrased in terms of constraint satisfaction. In particular MAX-2-SAT and MAX-2-CSP are known to generalize many hard combinatorial problems on graphs. Algorithms solving the problem exactly have been designed but the running time is improved over trivial brute-force solutions only for very sparse instances. Despite many efforts, the only known algorithm [R. Williams, Theor. Comput. Sci. 348, No. 2–3, 357–365 (2005; Zbl 1081.68095)] solving MAX-2-CSP over $$n$$ variables in less than $$O^\ast(2^n)$$ steps uses exponential space.
Several authors have designed algorithms with running time $$O^\ast(2^{nf(d)})$$ where $$f:\mathbb R^+\to (0,1)$$ is a slowly growing function and $$d$$ is the average variable degree of the input formula. The current best known algorithm for MAX-2-CSP [A. D. Scott and G. B. Sorkin, Discrete Optim. 4, No. 3–4, 260–287 (2007; Zbl 1153.90505)] runs in time $$O^\ast(2^{n(1-\frac{2}{d+1})})$$ and polynomial space. In this paper we continue this line of research and design new algorithms for the MAX-2-SAT and MAX-2-CSP problems.
First, we present a general technique for obtaining new bounds on the running time of a simple algorithm for MAX-2-CSP analyzed with respect to the number of vertices from algorithms that are analyzed with respect to the number of constraints. The best known bound for the problem is improved to $$O^\ast(2^{n(1-\frac{3}{d+1})})$$ for $$d\geqslant 3$$. We further improve the bound for MAX-2-SAT, in particular for $$d\geqslant 6$$ we achieve $$O^\ast(2^{n(1-\frac{3.677}{d+1})})$$.
As a second result we present an algorithm with asymptotically better running time for the case when the input instance is not very sparse. Building on recent work of U. Feige and S. Kogan [J. Graph Theory 64, No. 4, 277–291 (2010; Zbl 1205.05087)] we derive an upper bound on the size of a vertex separator for graphs in terms of the average degree of the graph. We then design a simple algorithm solving MAX-2-CSP in time $$O^\ast(2^{c_dn})$$, $$c_d=1-\frac{2\alpha\ln d}{d}$$ for some $$\alpha<1$$ and $$d=o(n)$$.

MSC:
 68W40 Analysis of algorithms 68Q17 Computational difficulty of problems (lower bounds, completeness, difficulty of approximation, etc.) 90C27 Combinatorial optimization
MAX-2-SAT
Full Text:
References:
 [1] Alon, N.; Kahn, J.; Seymour, P. D., Large induced degenerate subgraphs, Graphs Comb., 3, 1, 203-211, (1987) · Zbl 0624.05039 [2] Binkele-Raible, D.; Fernau, H., A new upper bound for MAX-2-SAT: A graph-theoretic approach, J. Discrete Algorithms, 8, 4, 388-401, (2010) · Zbl 1203.90130 [3] Björklund, A.; Husfeldt, T.; Koivisto, M., Set partitioning via inclusion-exclusion, SIAM J. Comput., 39, 2, 546-563, (2009) · Zbl 1215.05056 [4] Calabro, C.; Impagliazzo, R.; Paturi, R., The complexity of satisfiability of small depth circuits, (IWPEC, (2009)), 75-85 · Zbl 1273.68159 [5] Chen, J.; Kanj, I. A., Improved exact algorithms for MAX-SAT, Discrete Appl. Math., 142, 1-3, 17-27, (2004) · Zbl 1077.68116 [6] Croce, F. D.; Kaminski, M. J.; Paschos, V. Th., An exact algorithm for MAX-CUT in sparse graphs, Oper. Res. Lett., 35, 3, 403-408, (2007) · Zbl 1163.90767 [7] Dantsin, E.; Wolpert, A., MAX-SAT for formulas with constant clause density can be solved faster than in $$O(2^n)$$ time, (SAT, (2006)), 266-276 · Zbl 1187.68258 [8] Feige, U.; Kogan, S., Balanced coloring of bipartite graphs, J. Graph Theory, 64, 4, 277-291, (2010) · Zbl 1205.05087 [9] Fürer, M.; Kasiviswanathan, S. P., Exact MAX 2-sat: easier and faster, SOFSEM, 1, 272-283, (2007) · Zbl 1131.68522 [10] Gaspers, S.; Sorkin, G. B., A universally fastest algorithm for MAX 2-sat, MAX 2-CSP, and everything in between, J. Comput. Syst. Sci., 78, 1, 305-335, (2012) · Zbl 1238.68066 [11] Golovnev, A., New upper bounds for MAX-2-SAT and MAX-2-CSP w.r.t. the average variable degree, (IPEC, (2011)), 106-117 · Zbl 1352.68107 [12] Gramm, J.; Hirsch, E. A.; Niedermeier, R.; Rossmanith, P., Worst-case upper bounds for MAX-2-SAT with an application to MAX-CUT, Discrete Appl. Math., 130, 2, 139-155, (2003) · Zbl 1051.68078 [13] Håstad, J., Some optimal inapproximability results, J. ACM, 48, 4, 798-859, (2001) · Zbl 1127.68405 [14] Held, M.; Karp, R. M., A dynamic programming approach to sequencing problems, J. SIAM, 10, 196-210, (1962) · Zbl 0106.14103 [15] Hirsch, E. A., A new algorithm for MAX-2-SAT, (STACS, (2000)), 65-73 · Zbl 0959.68047 [16] Horowitz, E.; Sahni, S., Computing partitions with applications to the knapsack problem, J. ACM, 21, 277-292, (1974) · Zbl 0329.90046 [17] Impagliazzo, R.; Paturi, R.; Zane, F., Which problems have strongly exponential complexity?, J. Comput. Syst. Sci., 63, 4, 512-530, (2001) · Zbl 1006.68052 [18] Kojevnikov, A.; Kulikov, A. S., A new approach to proving upper bounds for MAX-2-SAT, (SODA, (2006)), 11-17 · Zbl 1192.68368 [19] Kulikov, A. S.; Kutzkov, K., New upper bounds for the problem of maximal satisfiability, Discrete Math. Appl., 155-172, (2009) · Zbl 1234.68154 [20] Kutzkov, K., An exact exponential time algorithm for counting bipartite cliques, Inf. Process. Lett., 112, 13, 535-539, (2012) · Zbl 1243.05227 [21] Lawler, E. L., A note on the complexity of the chromatic number problem, Inf. Process. Lett., 5, 66-67, (1976) · Zbl 0336.68021 [22] Lipton, R. J.; Tarjan, R. E., Applications of a planar separator theorem, SIAM J. Comput., 9, 3, 615-627, (1980) · Zbl 0456.68077 [23] Moser, R. A.; Scheder, D., A full derandomization of schöning’s k-SAT algorithm, (STOC, (2011)), 245-252 · Zbl 1288.68245 [24] Schöning, U., A probabilistic algorithm for k-SAT based on limited local search and restart, Algorithmica, 32, 4, 615-623, (2002) · Zbl 1050.68049 [25] Scott, A. D.; Sorkin, G. B., Linear-programming design and analysis of fast algorithms for MAX 2-CSP, Discrete Optim., 4, 3-4, 260-287, (2007) · Zbl 1153.90505 [26] Tarjan, R. E.; Trojanowski, A. E., Finding a maximum independent set, SIAM J. Comput., 6, 537-546, (1977) · Zbl 0357.68035 [27] Vassilevska Williams, V., Multiplying matrices faster than coppersmith-Winograd, (STOC, (2012)), 887-898 · Zbl 1286.65056 [28] Williams, R., A new algorithm for optimal 2-constraint satisfaction and its implications, Theor. Comput. Sci., 348, 2-3, 357-365, (2005) · Zbl 1081.68095
This reference list is based on information provided by the publisher or from digital mathematics libraries. Its items are heuristically matched to zbMATH identifiers and may contain data conversion errors. It attempts to reflect the references listed in the original paper as accurately as possible without claiming the completeness or perfect precision of the matching.


text:
Windows command to convert Unix line endings?

Is there a Windows command to convert line endings of a file?

We have a test.bat which we need to run to start our server. We use Perforce and we need to have unix line endings in our workspace. For some reason, we are not allowed to change line endings to Windows in our workspaces. However, the server runs on Windows.

Everytime I have to run the bat file, I open it in Notepad++ and choose Edit→EOL conversion→Windows. Is there a way to automate this so that we won't need to manually change the line endings everytime we sync with Perforce?

This can actually be done very easily using the more command which is included in Windows NT and later. To convert input_filename which contains UNIX EOL (End Of Line) \n to output_filename which contains Windows EOL \r\n, just do this:

TYPE input_filename | MORE /P > output_filename

The more command has additional formatting options that you may not be aware of. Run more/? to learn what else more can do.

You can do this without additional tools in VBScript:

Do Until WScript.StdIn.AtEndOfStream
Loop

Put the above lines in a file unix2dos.vbs and run it like this:

cscript //NoLogo unix2dos.vbs <C:\path\to\input.txt >C:\path\to\output.txt

or like this:

type C:\path\to\input.txt | cscript //NoLogo unix2dos.vbs >C:\path\to\output.txt

You can also do it in PowerShell:

(Get-Content "C:\path\to\input.txt") -replace "n", "rn" |
Set-Content "C:\path\to\output.txt"

which could be further simplified to this:

(Get-Content "C:\path\to\input.txt") | Set-Content "C:\path\to\output.txt"

The above statement works without an explicit replacement, because Get-Content implicitly splits input files at any kind of linebreak (CR, LF, and CR-LF), and Set-Content joins the input array with Windows linebreaks (CR-LF) before writing it to a file.

I was dealing with CRLF issues so I decided to build really simple tool for conversion (in NodeJS):

So if you have NodeJS with npm installed you can try it:

npm i -g eol-converter-cli
eolConverter crlf "**/*.{txt,js,java,etc}"

Path might be configured dynamically by using Glob regex (same regex as in shell).

So if you can use NodeJS, it's really simple and you can integrate this command to convert whole workspace to desired line endings.

Windows' MORE is not reliable, it destroys TABs inevitably and adds lines.

unix2dos is part also of MinGW/MSYS, Cygutils, GnuWin32 and other unix binary port collections - and may already be installed.

When python is there, this one-liner converts any line endings to current platform - on any platform:

TYPE UNIXFILE.EXT | python -c "import sys; sys.stdout.write(sys.stdin.read())" > MYPLATFILE.EXT

or

python -c "import sys; sys.stdout.write(open(sys.argv[1]).read())" UNIXFILE.EXT > MYPLATFILE.EXT

Or put the one-liner into a .bat / shell script and on the PATH according to your platform:

@REM This is any2here.bat
python -c "import sys; sys.stdout.write(open(sys.argv[1]).read())" %1

and use that tool like

any2here UNIXFILE.EXT > MYPLATFILE.EXT

This will change all .txt files in place in the current directory from from LF to CRLF in Command Prompt

for /f %f in ('dir /b "*.txt"') do ( type %f | more /p > %f.1 & move %f.1 %f )

If you don't want to verify every single change

move

To

move /y

To include subdirectories change

dir /b

To

dir /b /s

To do all this in a batch file including subdirectories without prompting use below

@echo off
setlocal enabledelayedexpansion

for /f %%f in ('dir /s /b "*.txt"') do (
type %%f | more /p > %%f.1
move /y %%f.1 %%f > nul
@echo Changing LF-^>CRLF in File %%f
)
echo.
pause

try this:

(for /f "delims=" %i in (file.unix) do @echo %i)>file.dos

Session protocol:

C:\TEST>xxd -g1 file.unix
0000000: 36 31 36 38 39 36 32 39 33 30 38 31 30 38 36 35  6168962930810865
0000010: 0a 34 38 36 38 39 37 34 36 33 32 36 31 38 31 39  .486897463261819
0000020: 37 0a 37 32 30 30 31 33 37 33 39 31 39 32 38 35  7.72001373919285
0000030: 34 37 0a 35 30 32 32 38 31 35 37 33 32 30 32 30  47.5022815732020
0000040: 35 32 34 0a                                      524.

C:\TEST>(for /f "delims=" %i in (file.unix) do @echo %i)>file.dos

C:\TEST>xxd -g1 file.dos
0000000: 36 31 36 38 39 36 32 39 33 30 38 31 30 38 36 35  6168962930810865
0000010: 0d 0a 34 38 36 38 39 37 34 36 33 32 36 31 38 31  ..48689746326181
0000020: 39 37 0d 0a 37 32 30 30 31 33 37 33 39 31 39 32  97..720013739192
0000030: 38 35 34 37 0d 0a 35 30 32 32 38 31 35 37 33 32  8547..5022815732
0000040: 30 32 30 35 32 34 0d 0a                          020524..

My contribution for this, converting several files in a folder: for %%z in (*.txt) do (for /f "delims=" %%i in (%%z) do @echo %%i)>%%z.tmp

You could create a simple batch script to do this for you:

TYPE %1 | MORE /P >%1.1
MOVE %1.1 %1

Then run <batch script name> <FILE> and <FILE> will be instantly converted to DOS line endings.

Based on Endoro's answer but to keep the blanks, try this:

@echo off
setlocal enabledelayedexpansion
(for /f "tokens=* delims=:" %%i in ('findstr /n "^" file.unix') do (
set line=%%i
set line=!line:*:=!
echo(!line!
))>file.dos

I cloned my git project using the git bash on windows. All the files then had LF endings. Our repository has CRLF endings as default.

I deleted the project, and then cloned it again using the Windows Command Prompt. The CRLF endings were intact then. In my case, if I had changed the endings for the project, then it would've resulted in a huge commit and would've caused trouble for my teammates. So, did it this way. Hope this helps somebody.

I'm taking an AWS course and have frequently had to copy from text boxes in the AWS web forms to Windows Notepad. So I get the LF-delimited text only on my clipboard. I accidentally discovered that pasting it into my Delphi editor, and then hitting Ctrl+K+W will write the text to a file with CR+LF delimiters. (I'll bet many other IDE editors would do the same).

For convert UNIX(LF) to Windows(CR-LF) use next command

type file.txt > new_file.txt

If you have bash (e.g. git bash), you can use the following script to convert from unix2dos:

ex filename.ext <<EOF
:set fileformat=dos
:wq
EOF

similarly, to convert from dos2unix:

ex filename.ext <<EOF
:set fileformat=unix
:wq
EOF

Inserting Carriage Returns to a Text File

@echo off
set SourceFile=%1 rem c:\test\test.txt
set TargetFile=%2 rem c:\test\out.txt

if exist "%TargetFile%" del "%TargetFile%"
for /F "delims=" %%a in ('type "%SourceFile%"') do call :Sub %%a
goto :eof

:Sub
echo %1 >> "%TargetFile%"
if "%2"=="" goto :eof
shift
goto sub
`


text:
# Question

Formatted question description: https://leetcode.ca/all/734.html

 734. Sentence Similarity

Given two sentences words1, words2 (each represented as an array of strings),
and a list of similar word pairs pairs, determine if two sentences are similar.

For example, "great acting skills" and "fine drama talent" are similar,
if the similar word pairs are pairs = [["great", "fine"], ["acting","drama"], ["skills","talent"]].

Note that the similarity relation is not transitive. For example, if "great" and "fine" are similar,
and "fine" and "good" are similar, "great" and "good" are not necessarily similar.

However, similarity is symmetric. For example, "great" and "fine" being similar is the same as "fine" and "great" being similar.

Also, a word is always similar with itself. For example, the sentences words1 = ["great"], words2 = ["great"], pairs = [] are similar,
even though there are no specified similar word pairs.

Finally, sentences can only be similar if they have the same number of words.
So a sentence like words1 = ["great"] can never be similar to words2 = ["doubleplus","good"].

Note:
The length of words1 and words2 will not exceed 1000.
The length of pairs will not exceed 2000.
The length of each pairs[i] will be 2.
The length of each words[i] and pairs[i][j] will be in the range [1, 20].

# Algorithm

Just create a mapping between a word and a set of all similar words. For example, if great and fine are similar, and great and good are similar, then there is the following mapping:

great -> {fine, good}

So when we check the corresponding words in the two sentences one by one, we can directly find them in the mapping. Note that the words that may be encountered are reversed, such as fine and great, so we must bring both words into the mapping.

To search, as long as one can be found, it means that it is similar. On the contrary, if both are not found, it means that they are not similar, and return false directly

Java


text:
# What is the factor group $C_{12}/C_{6}$?

I know this factor group is isomorphic to $$C_2$$, but I have tried calculating it and I only get one coset.

• We have the coset $e C_6=C_6$ and another one. – Dietrich Burde Apr 3 at 9:31

$$C_6$$, as a subgroup of $$C_{12}$$, contains $$6$$ of the $$12$$ elements. The remaining $$6$$ must make up the second coset.
Specifically, if $$C_{12} = \{0,1,2,3,4,5,6,7,8,9,10,11\}$$ with addition modulo $$12$$ as the group operation, then the two cosets of $$C_6$$ are $$C_6 = \{0,2,4,6,8,10\}\\ 1 + C_6 = \{1,3,5,7,9,11\}$$
$$C_{12}/C_6\cong C_2$$, as the order is $$2$$ and there is only one $$2$$-element group.


text:
# A question about Nash Equilibrium

I have some trouble with Nash Equilibrium. The specific question as follows.

Suppose that there are $$2N$$ people in the village, of which $$N$$ residents live in the first district, and each person chooses to raise $$q_1$$ sheep, and the cost of each sheep is $$c_1$$. In addition, n people live in the second district, and each person chooses to raise $$q_2$$ sheep. The cost of a sheep is $$c_2$$. The income brought by each sheep is $$200-q$$, where $$q$$ is the total number of sheep in the village.
Q: Find the number of sheep raised by each resident in the two regions under the Nash equilibrium of this game.

Here is my thought. For simplicity, let $$I$$ denotes the index set of individuals in the first district, similarly, $$II$$ for the second district.

For $$\forall i\in I$$, the profit maximization problem is $$$$\max_{q_i} \pi_i=(200-q_i-\sum_{k\neq i,\\i\in I}q_k-\sum_{l\in II}q_l)q_i-c_1q_i\\ F.O.C\qquad \frac{\partial \pi_i}{\partial q_i}=200-2q_i-\sum_{k\neq i\\k\in I}q_k-\sum_{l\in II}q_l-c_1=0\\ BR_{q_i}(q_{-i})=q_i=100-\frac{1}{2}\sum_{k\neq i\\k\in I}q_k-\frac{1}{2}\sum_{l\in II}q_l-\frac{1}{2}c_1$$$$

Similarly, for $$\forall j\in II$$, we have best reaction function $$$$BR_{q_j}(q_{-j})=q_j=100-\frac{1}{2}\sum_{k\in I}q_k-\frac{1}{2}\sum_{l\neq j\\l\in II}q_l-\frac{1}{2}c_2$$$$

Since every individual belonging to the same area is in the same situation, we can assume that \begin{align} \begin{cases} q_i^*=a, &\forall i\in I\\ q_j^*=b, &\forall j\in II \end{cases} \end{align} and then substitute it into the best reaction function, we have \begin{align} \begin{cases} (N+1)a+Nb=200-c_1\\ Na+(N+1)b=200-c_2 \end{cases} \end{align} \begin{align} \begin{cases} a=\frac{ \begin{vmatrix} 200-c_1 & N\\ 200-c_2 & N+1 \end{vmatrix}}{\begin{vmatrix} N+1 & N\\ N & N+1 \end{vmatrix}}\\ b=\frac{ \begin{vmatrix} N+1 & 200-c_1\\ N & 200-c_2 \end{vmatrix}}{\begin{vmatrix} N+1 & N\\ N & N+1 \end{vmatrix}} \end{cases} \end{align}

I don’t know if I’m doing it right, and I’m going to solve it under the assumption that there is an interior point solution. I think if it is strictly proved, the cost $$c_1,c_2$$ may be considered.

From symmetry we can say that for each player $$i$$ in $$I$$, $$q_r=q_k$$ $$\forall r,k \in I$$. Similarly for $$II$$. Let this be $$q_I$$ for producers in $$I$$ and $$q_{II}$$ for $$II$$.

So profit function for individual $$i$$ in $$I$$: \begin{align} \max_{q_i} \pi_i&=(200-(N-1)q_I-Nq_{II}-q_i))q_i-c_1q_i\\ \text{FOC: }\,\,\frac{\partial \pi_i}{\partial q_i}&=200-(N-1)q_I-Nq_{II}-q_i-q_i-c_1=0 \\ \implies q_i^*(q_I,q_{II})&=\frac{200-Nq_{II}-c_1-(N-1)q_I}{2} \end{align}

Similarly, we will get for individual $$j$$ in $$II$$:

$$q_j^*(q_I,q_{II})=\frac{200-Nq_I-c_2 - (N-1)q_{II}}{2N}$$

At NE, we know that $$q_i^*=q_I^*$$ and $$q_j^*=q_{II}$$. Using this:

\begin{align} q_I^*&=\frac{200-Nq_{II}^*-c_1-(N-1)q_I^*}{2} \\ &=\frac{200-Nq_{II}^*-c_1}{N+1} \end{align}

And so, $$q_{II}^*=\frac{200-Nq_{I}^*-c_2}{N+1}$$

Solving for $$q_I^*$$:

\begin{align} (N+1)q_I^*&=200-N\frac{200-Nq_I^*-c_2}{N+1}-c_1 \\ \implies q_I^* &=\frac{200-c_1+N(c_2-c_1)}{2N+1} \end{align} Similarly, $$q_{II}^* =\frac{200-c_2+N(c_1-c_2)}{2N+1}$$

• I just don’t understand why $n(q_1+q_2)$ can be directly substituted into the reaction function. Isn’t it calculated under the conditions of other people? If you substitute $n(q_1+q_2)$ at the beginning, it seems unreasonable. Dec 11 '20 at 23:38
• Conceptually it may seem unreasonable but think of this as a mathematical trick to simplify calculation. We know that it's going to be true so we might as well use it. Dec 12 '20 at 1:13
• From the final result you have derived, I think it is equivalent to considering only one person in each of the two districts of the village at the beginning, and get their corresponding Nash Equilibrium, and then divide the total number of each district evenly among the $N$ people in the same district. In this way, we can see the $N$ is on the denominator. Dec 12 '20 at 1:38
• @BongseoChoi yes that sounds absolutely correct Dec 12 '20 at 2:21
• Thank you for discussing this question. Dec 12 '20 at 2:49


text:
• Create Account

## MADE A SIMPLE NEURAL NETWORK, BUT NOT SURE IF I DID IT RIGHT

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

9 replies to this topic

### #1kazisami  Members

558
Like
0Likes
Like

Posted 26 February 2013 - 10:53 PM

A simple single unit adaptive network:

The network has 2 inputs, and one output. All are binary. The output
is

1 if W0 *I0 + W1 * I1+ Wb > 0

0 if W0 *I0 + W1 * I1+ Wb <= 0

We want it to learn simple OR: output a 1 if either I0 or I1 is 1.

For Solving this problem i have made this-

#include <iostream>

struct Newron
{
int value;
int weight;
};

int main()
{
Newron input_one, input_two, output;
int bias = 0;

input_one.weight = 1;
input_two.weight = 1;

std::cin >> input_one.value;
std::cin >> input_two.value;

output.value = (input_one.value * input_one.weight) + (input_two.value * input_two.weight) + bias;

if(output.value > 0)
std::cout << 1 << std::endl;
else
std::cout << 0 << std::endl;

return 0;
}

Is it the right way?

If not then how it can be done?

Edited by kazisami, 27 February 2013 - 02:30 AM.

To follow the path:

look to the master,

follow the master,

walk with the master,

see through the master,

become the master.

### #2Cornstalks  Members

7026
Like
0Likes
Like

Posted 26 February 2013 - 11:05 PM

I can't comment, but I'll suggest you a) DON'T MAKE YOUR TITLE LOOK LIKE IT'S SHOUTING, and b) use [ code ][ /code ] (without spaces) tages for code to help with formatting/highlighting.

Good luck!

[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

### #3kazisami  Members

558
Like
0Likes
Like

Posted 27 February 2013 - 02:31 AM

I can't comment, but I'll suggest you a) DON'T MAKE YOUR TITLE LOOK LIKE IT'S SHOUTING, and b) use [ code ][ /code ] (without spaces) tages for code to help with formatting/highlighting.

Good luck!

Sorry for the title And i changed the code formatting, but couldn't be able to change the title.

To follow the path:

look to the master,

follow the master,

walk with the master,

see through the master,

become the master.

### #4Tournicoti  Prime Members

704
Like
1Likes
Like

Posted 27 February 2013 - 07:09 AM

Hello

This seems to be a good start for me

In fact you are precisely describing (wanting ?) Perceptron model

This is pseudo-code :

class Neuron
{
float [] inputs; // (with : true is 1.0f, false is 0.0f)
float [] weights;

Constructor(integer nbInputs)
{
inputs=new array [nbInputs +1] (+1 is for including the bias). Or getting a reference on an external array.
weights=new array [nbInputs +1]

fill the weights array with float random values between -1 and 1
set 1.0f in the position corresponding to the bias in the inputs array(typically, first or last position)
}

float computeOutput()
{
sum=dotProduct(inputs,weights);
return sum>0.0f;
}

void learn(float desiredOutput,float learningRate) // adaptation of the weights
{
float output=computeOutput();
float deltaOutput=desiredOutput-output; (so -1.0f or 0.0f or 1.0f)

for each position in the arrays
{
weights[i]+=learningRate*inputs[i]*deltaOutput;
}
}

};

Hope it makes sense

for a OR, it should converge with : w1=w2=lambda, and wBias=0. With lambda>0

Good luck

Edited by Tournicoti, 02 March 2013 - 09:10 AM.

### #5kazisami  Members

558
Like
0Likes
Like

Posted 27 February 2013 - 07:45 AM

Hello

This seems to be a good start for me

In fact you are precisely describing (wanting ?) Perceptron model

This is pseudo-code :

class Neuron
{
float [] inputs; // (with : true is 1.0f, false is 0.0f)
float [] weights; //idem

Constructor(integer nbInputs)
{
inputs=new array [nbInputs +1] (+1 is for including the bias). Or getting a reference on an external array.
weights=new array [nbInputs +1]

fill the weights array with float random values between -1 and 1
set 1.0f in the position corresponding to the bias in the inputs array(typically, first or last position)
}

float computeOutput()
{
sum=dotProduct(inputs,weights);
return sum>0.0f;
}

void learn(float desiredOutput,float learningRate) // adaptation of the weights
{
float output=computeOutput();
float deltaOutput=desiredOutput-output; (so -1.0f or 0.0f or 1.0f)

for each position in the arrays
{
weights[i]+=learningRate*inputs[i]*deltaOutput;
}
}

};

Hope it makes sense

for a OR, it should converge with : w1=lambda, w2=lambda, et wBias=0, lambda>0

Good luck

Thank you very much Most of the part is clear to me, but I didn't understood the learningRate argument in the learn() method. Do I have to adjust it so that the network can learn or adjust weight on its own?

To follow the path:

look to the master,

follow the master,

walk with the master,

see through the master,

become the master.

### #6Tournicoti  Prime Members

704
Like
1Likes
Like

Posted 27 February 2013 - 08:52 AM

The learning rate is just an user-defined constant, here. It's usually a value between 0 and 1.

It's like defining the 'step' of the adaptation.

I would suggest to try low values first  (0.2 ? even less ?) because inputs[i]*deltaOutput is here a huge value : -1 or 0 or 1 !

Afterwards, the goal is to maximize the learning rate so that the learning process is quicker but still accurate enough for the wanted approximation.

Hope I'm still clear (sorry for my english, I'm getting tired )

Bye

Edited by Tournicoti, 27 February 2013 - 10:26 AM.

### #7kazisami  Members

558
Like
1Likes
Like

Posted 27 February 2013 - 09:59 AM

Don't worry, your english is as awesome as your explanation I am getting a hold of this, but I need to experiment a lot before I can understand it clearly. But you answered my question and that's enough for starting experiment without any confusion.

Thanks a lot for your help

To follow the path:

look to the master,

follow the master,

walk with the master,

see through the master,

become the master.

### #8Tournicoti  Prime Members

704
Like
0Likes
Like

Posted 27 February 2013 - 10:25 AM

Edited by Tournicoti, 27 February 2013 - 10:38 AM.

### #9Tournicoti  Prime Members

704
Like
2Likes
Like

Posted 28 February 2013 - 06:56 PM

I would like to add another little thing :

What I described is the Perceptron as it was designed by Frank Rosenblatt (original version)

However there's another (very slightly different !) version in which -1 and 1 are used instead of 0 and 1 to encode booleans.

In term of learning efficiency it's better because  :

• with 0 and 1, the weights will evolve only when deltaOutput is not zero and input is not zero.
• with -1 and 1, the weights will always evolves when deltaOutput is not zero.

And this is 'nothing' to change :

• change input encoding (so no more 0 and 1, but -1 and 1)
• change the activation function :  sum>0.0f ? 1.0f : -1.0f

Bye

### #10kazisami  Members

558
Like
0Likes
Like

Posted 01 March 2013 - 01:35 AM

Thanks again for the help. You know what, I was going to ask you the same thing. I was looking for some other neural networks, then I came across Hopfield network and there is a step when we need to convert the boolean(1 and 0) to 1 and -1. Then I was thinking if this could be done with Perceptron too. And before I could ask, you answered it

Edited by kazisami, 01 March 2013 - 01:36 AM.

To follow the path:

look to the master,

follow the master,

walk with the master,

see through the master,

become the master.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.


text:
Analytic Geometry

Vocabulary

asymptote

line that a graph approaches as one of the variables approaches infinity or negative infinity

axis of symmetry

line that divides a graph into two halves that are mirror images

circle

set of all points that are a fixed distance $r$ from a point called the center

co-vertex

one of two points on the ellipse that are endpoints of the minor axis

conic section

resulting cross section when a plane intersects a double cone

conjugate axis

line perpendicular to the transverse axis of a hyperbola and that intersects it at the center of the hyperbola

directrix

line used with the focus to define a parabola. For any point on the parabola, the distance to the focus is equal to the distance to the directrix.

double cone

geometric figure made up of two cones that are opposite each other with their vertices at the same point

ellipse

set of points such that the sum of the distances from two fixed points called the foci remains the same

focus

fixed point used to generate a conic section

fundamental rectangle

rectangle used as a guide to graph a hyperbola. The diagonals of the rectangle are the asymptotes of the hyperbola, and the vertices of the hyperbola are the midpoints of two sides of the rectangle.

hyperbola

set of points such that the difference of the distances from two fixed points called the foci remains the same

major axis

segment that passes through the foci of an ellipse with endpoints on the ellipse

minor axis

segment with endpoints on an ellipse that is perpendicular to the major axis

parabola as a conic section

set of points such that the distance from a fixed point called the focus is equal to the distance to a line called the directrix

distance from the center of a circle to a point on the circle

transverse axis

line that passes through the foci of a hyperbola

vertex of a hyperbola

one of two points where the transverse axis intersects a hyperbola

vertex of a parabola

midpoint of the segment from the focus to the directrix of the parabola

vertex of an ellipse

one of two points on the ellipse that are endpoints of the major axis


text:
# Expressing Gain in Decibels?

1) Why does power gain use a coefficient of 10 unlike the other two?

2) Why can't power gain be negative?

• Note that the power gain has the absolute value built in: power is related to the square of voltage, and the square of any real number is positive. – Greg d'Eon Jan 14 '15 at 20:16

## 5 Answers

1. It's just a convention. Decibels always refer to power, and power is proportional to voltage squared and current squared. The math works like this:

\begin{align} A_{v,dB} &= 10\cdot\log \frac{V_o^2}{V_i^2} \\ &= 10\cdot\log \left(\frac{V_o}{V_i}\right)^2 \\ &= 10\cdot 2 \cdot\log \frac{V_o}{V_i} \end{align}

EDIT: Power is proportional to voltage/current squared for all linear circuits. In AC circuit analysis, voltage, current, and power all become phasors. In nonlinear circuits, power may not be proportional to voltage/current squared, but the convention is still used for decibels. It even holds in an abstract field like signal processing, where the "power" of a signal is defined to be the average of the amplitude squared.

1. Decibels are used to give the magnitude of the gain. If you want to talk about power loss, you use negative decibels, which represents a fractional gain. For example:

$$A_p = 0.01$$ $$A_{p,dB} = 10\cdot\log 0.01 = -20\:\mathrm{dB}$$

You can also have an actual negative gain, like what you get from an inverting amplifier. The negative there is described as a phase shift. To fully describe an amplifier, you usually need both the magnitude and the phase of the gain. (This might be a bit advanced for you, but you could try looking up Bode Plots to see how this is used in real life.) Anyway, here's how to describe an inverting amplifier with a voltage gain of -2.4:

$$A_v = -2.4$$ $$|A_v| = 20\cdot\log 2.4 \approx 7.6\:\mathrm{dB}$$ $$\angle A_v = 180^\circ$$

• Thank you. Power is only proportional to voltage/current squared for resistors. But power can be applied to other devices too can't it? Also, I know you can get negative gain, but can you get negative power gain? You cannot have a phase shift on power can you? Since it's not a phasor? – dfg Jan 14 '15 at 18:55
• Power can indeed be a phasor, although it doesn't work quite the same way. (Look up "reactive power".) I suppose a negative power gain would mean that the input and output are both absorbing power. I can't think of a real-life example of that, though. I'll update my answer to cover P = V^2 a bit more. – Adam Haun Jan 14 '15 at 19:09
• An interesting counter-reference, I was taught in college that voltage and current use 10log(V) or 10log(I), and power used 20log(V). This is consistent with dB's usage in non-power settings, such as dBsm, which is area (in square meters), on a 10log(x) scale. dBsm shows up in a lot of radar calculations. – Cort Ammon Jan 15 '15 at 7:12
1. Decibels is always about power. The expressions for voltage and current use a factor of 20 instead of 10 because power ratios are proportional to the square of the voltage or current ratio.

2. Power gain can be negative, but then it's generally called "loss". The logarithm of any number less than unity is negative.

• @ first bullet: strictly speaking the value of the impedance must not change, but that is not always accounted for. – jippie Jan 14 '15 at 17:53
• But the square law difference is only true for resistors. Power can be applied to other types of devices too can't it? Also, by "power gain", I mean't $A_p$, not $10\log A_p$. If $A_p$ is negative, the log would be imaginary... – dfg Jan 14 '15 at 18:34
• By definition, "power gain", or $A_p$ is $\frac{|Power_{OUT}|}{|Power_{IN}|}$. It can't be negative. If the amplifier happens to be an inverting amplifier, it doesn't mean that the power gain is negative. – Dave Tweed Jan 14 '15 at 18:42
• The logarithm of a negative number is undefined. It's the squaring of the voltages (to get power), not the log (to get dB) that makes the ratio of power out to power in positive even if the amplifier is inverting. – Phil Frost Jan 15 '15 at 11:57

Decibel is a measure of power ratio.

It is 10x (for power ratios) because the unit is bel (deci is one of the 'approved' prefix for 1/10).

It is 20x (ie 2*10) when dealing with voltages and current as the dissipated power is typically proportional to the square of these quantities. Due to log rules a $10*log(\frac{V_1}{V_2})^2$ would see the power2 come down as a scalar gain $2*10*log(\frac{V_1}{V_2})$

dB is an indication of the ratio of power between two points. If you cannot take credit for a load impedance being held constant then actual power needs to be used

• But the square law difference is only true for resistors. Power can be applied to other types of devices too can't it? – dfg Jan 14 '15 at 18:32
• @dfg. Gain=10·log(Powerout/Powerin). Powerout=Vout·Iout and Powerin=Vin·Iin. And you can apply those formulas to any device. – Roger C. Jan 14 '15 at 19:43
• @RogerC. Yes, but neither of those equations have power proportional to the square of voltage. You can get $P=V^2/R$ if you substitute Ohm's law into one of your equations, but then Ohm's law doesn't apply to everything. For example, the load could be a diode. – Phil Frost Jan 15 '15 at 12:00
• @PhilFrost, I don't really understand your point. Gain in dB is always about power. In a diode I=f(V). So that power would be V·f(V). There is not a square here. – Roger C. Jan 15 '15 at 13:09
• Yes, exactly. But in your answer you say, unqualified, "It is 20x (for volts and amps) as there is a square law difference between volts, amps and power". You should edit your question to qualify that statement with the conditions where it is true. – Phil Frost Jan 15 '15 at 14:36

Power decibels are tough because they throw a few concepts at you at once without making clear that's what happening.

Concept 1: Bel is the unit of log ratios (which is really a cancelled out unit of Power/Power).

Concept 2: deci- is a prefix that denotes 1/10th. 1 Bel = 10 * deci-Bel.

Concept 3: logs turn exponents into multiplication, making the math easier to work with and graph. log(x^n) = n*log(x).

Concept 4: logs imply "Power"...even when working with voltage or current. Think Pa/Pb = (Va^2/R) / (Vb^2/R) where the R's cancel out (sort of).

First, break up the word "decibel". "deci-" is the prefix for 1/10th. The "bel" is for the unit "Bel", named after Alexander Graham Bell and is the log ratio of two numbers. Because bel is for the unit "Bel", the the "B" in dB capitalized. Same concept as in kilohertz (kHz = "kilo-" + Hertz).

Assume all logs have base 10 in the examples below.

Example 1 (simple ratio):

value1 = 100,000

value2 = 100

simple_ratio = value1/value2 = 100,000/100 = 1,000

Example 2 (log):

value1 = 100,000

value2 = 100

simple_log = log(value1/value2) = log(100,000/100) = log(1000) = 3 Bel. Same as 10^x = 1,000, x = 3 Bel In English "10 to what power (x) is 1,000? 10^(3) = 10,000. Answer is 3."

Example 3 (decibel):

value1 = 100,000

value2 = 100

simple_log = log(100,000/100) = 3 Bel

To make it a "deci-" Bel... divide by 10: simple_log/10 = simple_deci_log

Rearranged:

simple_log = 10*simple_decibel

So.....Why 10x for Power and 20x for Voltage and Current?

The Bel, itself, is not specific to power but, for various reasons, the science and engineering community decided to choose to adhere to it as the convention. Unless otherwise specified dB denotes power (e.g. dBV).

Recall:

P = I^2 * R

P = V^2 / R

Logs turn exponents into multiplication...which is why we use them. The square relationship of current to power and voltage to power is where the 2 x comes from...so if a Power ratio is expressed in voltage or current it must account for the square relationship.. which means you pull the square from the inside of the log out to the front.

some_log = log(x ^ 2) = 2*log(x) Bel

some_power_ratio_expressed_in_voltage_in_Bel = log(Va^2/Vb^2) = 2*log(Va/Vb) "Bel"

10 * deci-Bel = 1 * Bel

some_power_ratio_expressed_in_voltage_in_deci_Bel = 10 * log(Va^2/Vb^2) = 2 * 10 * log(Va/Vb) = 20 * log(Va/Vb)

Lets take small steps and look at the equations...

Gain (in dB) is given by

Power is given by: .

The statement holds in linear cicuits.

Thus holds linear circuits.

If we substitute power in the first equation we get

and


text:
# Representing game with map through Extensive Form

I have a task to represent game using extensive form. I know how to work with extensive form in general, but I have problem how to represent this type of the game.

Rules: (Player 1 = P1, Player 2 = P2, game is zero sum)

1. S means start position, D means end position.
2. E means dangerous place, where bandit (owned by P2) can be. There is 1 bandit in the game and when met it has P(0.7) to kill P1.
3. We can step on each free space (represented by '-') only once.
4. Our task, get to D (utility 10 if successfull) and if possible pick up gold on G which provides extra +1 utility.
5. When we step on first E in the game and it happens to be empty, bandit can relocate.
6. '#' is obstacle.

Map representation:

#######
#E---E#
#S#-#D#
#E--EG#
#######

My idea was, P2 will place bandit on either E on [2,2] or [2,4] since P1 has to go through one of those spots first. Then it can happen:

• Bandit gets into conflict and has P(0.7) to kill P1 which will resolve into game value of 0.
• Bandit will be on the other E and therefore it will relocate to either [6,2] or [5,4].

Then agent can go either through [6,2] or [5,4] because there is free space in middle through which it can traverse to upper/lower part of the map. P2 is motivated slightly more to defend [5,4] than [6,2].

I calculated that there are basically five outcomes of the whole game:

1. P1 gets caught on the first pair of E's and dies. u=0; P(14/40)
2. P1 gets caught on the first pair of E's and survives, therefore can go for gold and to 'D' without worrying about bandit. u=11; P(6/40)
3. P1 does not get caught on first pair of E's but gets caught on second and dies. u = 0; P(7/40)
4. P1 does not get caught on first pair of E's but gets caught on second and survives. u=10/11 (depends on chosen path); P(3/40)
5. P1 does not get caught on second pair either. u = 10/11; P(10/40)

I also figured value of the game because we know that P2 decision between E tiles in second selection is based on P1 possible utility of the game being either 10 or 11. So we can calculate the utility so we know that P2 will guard E[5,4] with P(0,523...) and E[6,2] with P(0,476...). Therefore we can calculate that value for those cases (u=10/11) which is roughly 10,476... Than we can apply it to probabilites of outcomes and we get final value of game 5.05...

Questions:

1. Is this the right way how to abstract this game?
2. How would the extensive form representation look like?
3. [optionally if anyone would knew] How to formalize this as linear problem/program so we can compute value of the game from either max for P1 or min for P2?


text:
## Loren on the Art of MATLABTurn ideas into MATLAB

Note

Loren on the Art of MATLAB has been archived and will not be updated.

# Of Love, Music, Shakespeare and Dynamic Systems

For any human being love is one of the biggest source of joy, happiness...problems and puzzles. Today's guest blogger, Aldo Caraceto, one of my fellow Application Engineers from Italy, is going to convince you to approach it from a different angle.

### Contents

#### From Love to MATLAB

I love music. One of my favourite songs is the popular Toto track "Hold The Line". Very briefly, this song is about love and timing, as you may infer from the main chorus of the song: "Hold the line, love isn't always on time". Ok, it's not always on time, but can I predict when it will be? To answer this question, I've found a couple of insightful works, "Strogatz, S.H. (1988), Love affairs and differential equations, Math. Magazine 61, 35" and "Eva M. Strawbridge, Romeo and Juliet, a Dynamical Love Affair" which I've translated in MATLAB code. The mentioned papers answer a very simple question: how to express mathematically love dynamics, taking inspiration from "Romeo & Juliet" by W.Shakespeare. MATLAB may be a good friend to help us in examining the evolution of this relationship. An ode23 solver has been used to solve the system of equations representing the story. The results are quite funny.

#### A very simple emotional mechanism

This first example examines the condition where each person’s feelings are only affected by the other. Besides, we want our Romeo not following the expected behaviour: in this case, he'll be a confused and confusing lover: the more Juliet loves him, the more he begins to dislike her, generating surprising reactions with regards to the original tragedy.

$\frac{dr}{dt} = - a \cdot j,$

$\frac{dj}{dt} = b \cdot r$

In the system of differential equations representing the phenomenon, a and b are real, positive numbers, and measured in 1/time, hence are frequencies: the bigger they are, the shorter in time will be the swing of emotions for the two lovers. In addition, just a quick summary of the variables represented in the plots:

• R(t) = Romeo’s feelings for Juliet at time t .
• J(t) = Juliet’s feelings for Romeo at time t.
• R(t), J(t) > 0 signify love, passion, and attraction.
• R(t), J(t) < 0 values signify dislike.
• R(t),J(t) == 0 signifies indifference.
a = 2e-1;
b = 5e-1;
loveRJ = @(t,y) [-a*y(2); b*y(1)];

Now, we can set the problem up, collect data, and plot results, adding some annotations:

tstart = 0;
tfinal = 50;
tspan = [tstart tfinal];
y0 = [-1;2]; % initial conditions
[t,y] = ode23(@(t,y) loveRJ(t,y),tspan,y0);
plot(t,y')
ax = gca;
ax.XLim = [0 50];
ax.YLim = [-3 3];
ax.XLabel.String = 'Time';
ax.YLabel.String = 'Emotions';
ax.Title.String = 'Romeo & Juliet''s relationship';
legend('Romeo','Juliet')

#### When things get complicated...

In our first example, we have described the story with the changing emotions felt by Romeo and Juliet as they feed on each other's passion and indifference while the time is passing by. As you know, things - and people - are never so simple. Let's try to describe the relationship between Romeo and Juliet a bit differently, trying to compare the first, simple representation of the relationship with a more complex version. Then, we'll plot them together.

The new mathematical model can be expressed as:

$\frac{dr}{dt} = a \cdot r + b \cdot j ,$

$\frac{dj}{dt} = c \cdot r + d \cdot j$

As you may notice, this time there are four parameters, because we'd like to consider also how Romeo and Juliet are influenced by their own feelings:

a = -0.15;
d = 0.17;
b = 0.9;
c = -0.9;

We calculate the solutions for the two relationship model (you may find the model definitions at the end of the article):

tstart = 0;
tfinal = 50;
tspan = [tstart tfinal];
y0 = [1.00;-0.5]; % initial conditions

[t2,y2] = ode23(@(t,y) loveRJ_simple(t,y,a,d) ,tspan,y0);
[t1,y1] = ode23(@(t,y) loveRJ_ownEffect(t,y,a,b,c,d) ,tspan,y0);

and we plot them all on the same axis

figure
ax1 = subplot(2,1,1); % simple plot
plot(ax1, t1,y1')
ax1.YLim = [-2 2];
ax1.XLabel.String = 'Time';
ax1.YLabel.String = 'Emotions';
ax1.Title.String = 'Romeo & Juliet''s relationship - simple';
legend('Romeo','Juliet')

ax2 = subplot(2,1,2); % complex plot
plot(ax2, t2,y2')
ax2.YLim = [-1.5 1.5];
ax2.XLabel.String = 'Time';
ax2.YLabel.String = 'Emotions';
ax2.Title.String = 'Romeo & Juliet''s relationship - self-effect(complex)';
legend('Romeo','Juliet')

Here we've seen the impact of different models on the evolution of emotions; it looks like the chosen values tend to reduce the frequency of changes in emotions. Let's call it self-control (or selfishness).

#### Phase portrait and ODE solutions

Phase plane analysis is a very important technique to study the behavior of dynamic systems; it covers a particularly relevant role in the nonlinear case, where widely applicable methods for computing analytical solutions are not available. In a nutshell, it basically consist of drawing the derivatives of solutions against the solutions in the phase plane. The derivatives of solutions are usually drawn in form of vector fields, to emphasize how large are changes in the solutions at a specific point in the phase plane and show the trajectories of the solutions, given specific initial conditions. Therefore, by superposing the two plots, it is possible to infer how the solutions might evolve, for the purposes to build our understanding under which conditions a system might stable or not.

We start calculating the derivatives y1' and y2' for each point of the phase plane. We create a grid of points where we want to draw out plots:

y1 = linspace(-10,10,20);
y2 = linspace(-10,10,20);

meshgrid creates two matrices: one for all the uu-values of the grid, and one for all the vv-values of the grid. Then, we consider x1 and x2 matrices: x1 will contain the value of y1' at each uu and vv position, while x2 will contain the value of y2' at each uu and vv position of our grid.

[uu,vv] = meshgrid(y2,y1);
x1 = zeros(size(uu));
x2 = zeros(size(vv));

Now we compute the vector field and plot the phase portrait. Our derivatives are computed for each point (y1, y2) at init_time = 0, through a for loop. We have obtained the phase portrait.

a = -2e-1;
b = 5e-1;
init_time=0;
loveRJ = @(t,y) [a*y(2); b*y(1)];

for i = 1:numel(uu)
Yder = loveRJ(init_time,[uu(i); vv(i)]);
x1(i) = Yder(1);
x2(i) = Yder(2);
end

Finally we compute a couple of solutions and plot them, along with the phase portrait, on the phase plane.

figure
quiver(gca,uu,vv,x1,x2,'r');
xlabel('Juliet Emotions');
ylabel('Romeo Emotions');
axis tight equal;

% Calculate and plot 1st Solution
tstart = 0;
tfinal = 50;
tspan = [tstart tfinal];

y0_1 = [2;-1]; % initial conditions
[t,y1] = ode23(@(t,y) loveRJ(t,y),tspan,y0_1);
figure(gcf)
hold on
plot(y1(:,2),y1(:,1),'b')
plot(y1(1,2),y1(1,1),'mo',... % starting point
'MarkerEdgeColor','k',...
'MarkerFaceColor',[.49 1 .63],...
'MarkerSize',10)
plot(y1(end,2),y1(end,1),'bs',... % ending point
'MarkerEdgeColor','k',...
'MarkerFaceColor',[.49 .63 1],...
'MarkerSize',10)

% Calculate 2nd Solution
y0_2 = [4;1]; % initial conditions
[t,y2] = ode23(@(t,y) loveRJ(t,y),tspan,y0_2);figure(gcf)
plot(y2(:,2),y2(:,1),'c')
plot(y2(1,2),y2(1,1),'ko',... % starting point
'MarkerEdgeColor','k',...
'MarkerFaceColor',[.49 1 .63],...
'MarkerSize',10)
plot(y2(end,2),y2(end,1),'bs',... % ending point
'MarkerEdgeColor','k',...
'MarkerFaceColor',[.49 .63 1],...
'MarkerSize',10)
hold off
title("Two solutions plotted on vector field")

#### Relationship Models

This is the first model of their relationship, just dependent on the a / b parameters, defining Romeo's / Juliet's attraction for her/his counterpart.

function dy = loveRJ_simple(t,y,a,b)
dR = a*y(2);
dJ = b*y(1);
dy = [dR;dJ];
end

In the second model of relationship, two additional parameters appear:

• a,d = how Romeo, Juliet are influenced by their own feelings;
• b,c = Romeo's, Juliet's attraction for her/his counterpart.
function dy = loveRJ_ownEffect(t,y,a,b,c,d)
dR  = a*y(1) + b*y(2);
dJ = c*y(1) + d*y(2);
dy = [dR;dJ];
end

#### Conclusion

Today we have taken some steps in the analysis of this ''special'' dynamic system. Others can be done, exploiting tools already available in MATLAB. For example, making the system even more realistic, using the same ODE solver would have been a good deal or would you have chosen another one and why? Do you think calculating eigenvalues would have shed some more light on your understanding of the system? How would you do it in MATLAB? Try to answer these questions and ask yourself some new ones! Let us know what you think here.

Published with MATLAB® R2018a

|


text:
# Assignment problem

The assignment problem is a fundamental combinatorial optimization problem. In its most general form, the problem is as follows:

The problem instance has a number of agents and a number of tasks. Any agent can be assigned to perform any task, incurring some cost that may vary depending on the agent-task assignment. It is required to perform as many tasks as possible by assigning at most one agent to each task and at most one task to each agent, in such a way that the total cost of the assignment is minimized.

Alternatively, describing the problem using graph theory:

The assignment problem consists of finding, in a weighted bipartite graph, a matching of a given size, in which the sum of weights of the edges is minimum.

If the numbers of agents and tasks are equal, then the problem is called balanced assignment. Otherwise, it is called unbalanced assignment.[1] If the total cost of the assignment for all tasks is equal to the sum of the costs for each agent (or the sum of the costs for each task, which is the same thing in this case), then the problem is called linear assignment. Commonly, when speaking of the assignment problem without any additional qualification, then the linear balanced assignment problem is meant.

## Examples

Suppose that a taxi firm has three taxis (the agents) available, and three customers (the tasks) wishing to be picked up as soon as possible. The firm prides itself on speedy pickups, so for each taxi the "cost" of picking up a particular customer will depend on the time taken for the taxi to reach the pickup point. This is a balanced assignment problem. Its solution is whichever combination of taxis and customers results in the least total cost.

Now, suppose that there are four taxis available, but still only three customers. This is an unbalanced assignment problem. One way to solve it is to invent a fourth dummy task, perhaps called "sitting still doing nothing", with a cost of 0 for the taxi assigned to it. This reduces the problem to a balanced assignment problem, which can then be solved in the usual way and still give the best solution to the problem.

Similar adjustments can be done in order to allow more tasks than agents, tasks to which multiple agents must be assigned (for instance, a group of more customers than will fit in one taxi), or maximizing profit rather than minimizing cost.

## Formal definition

The formal definition of the assignment problem (or linear assignment problem) is

Given two sets, A and T, of equal size, together with a weight function C : A × TR. Find a bijection f : AT such that the cost function:
${\displaystyle \sum _{a\in A}C(a,f(a))}$

is minimized.

Usually the weight function is viewed as a square real-valued matrix C, so that the cost function is written down as:

${\displaystyle \sum _{a\in A}C_{a,f(a)}}$

The problem is "linear" because the cost function to be optimized as well as all the constraints contain only linear terms.

## Algorithms

A naive solution for the assignment problem is to check all the assignments and calculate the cost of each one. This may be very inefficient since, with n agents and n tasks, there are n! (factorial of n) different assignments. Fortunately, there are many algorithms for solving the problem in time polynomial in n.

The assignment problem is a special case of the transportation problem, which is a special case of the minimum cost flow problem, which in turn is a special case of a linear program. While it is possible to solve any of these problems using the simplex algorithm, each specialization has a smaller solution space and thus more efficient algorithms designed to take advantage of its special structure.

### Balanced assignment

In the balanced assignment problem, both parts of the bipartite graph have the same number of vertices, denoted by n.

One of the first polynomial-time algorithms for balanced assignment was the Hungarian algorithm. It is a global algorithm – it is based on improving a matching along augmenting paths (alternating paths between unmatched vertices). Its run-time complexity, when using Fibonacci heaps, is ${\displaystyle O(mn+n^{2}\log n)}$ ,[2] where m is a number of edges. This is currently the fastest run-time of a strongly polynomial algorithm for this problem. If all weights are integers, then the run-time can be improved to ${\displaystyle O(mn+n^{2}\log \log n)}$ , but the resulting algorithm is only weakly-polynomial.[3] If the weights are integers, and all weights are at most C (where C>1 is some integer), then the problem can be solved in ${\displaystyle O(m{\sqrt {n}}\log(n\cdot C))}$  weakly-polynomial time in a method called weight scaling.[4][5][6]

In addition to the global methods, there are local methods which are based on finding local updates (rather than full augmenting paths). These methods have worse asymptotic runtime guarantees, but they often work better in practice. These algorithms are called auction algorithms, push-relabel algorithms, or preflow-push algorithms. Some of these algorithms were shown to be equivalent.[7]

Some of the local methods assume that the graph admits a perfect matching; if this is not the case, then some of these methods might run forever.[1]: 3  A simple technical way to solve this problem is to extend the input graph to a complete bipartite graph, by adding artificial edges with very large weights. These weights should exceed the weights of all existing matchings, to prevent appearance of artificial edges in the possible solution.

As shown by Mulmuley, Vazirani and Vazirani,[8] the problem of minimum weight perfect matching is converted to finding minors in the adjacency matrix of a graph. Using the isolation lemma, a minimum weight perfect matching in a graph can be found with probability at least 12. For a graph with n vertices, it requires ${\displaystyle O(\log ^{2}(n))}$  time.

### Unbalanced assignment

In the unbalanced assignment problem, the larger part of the bipartite graph has n vertices and the smaller part has r<n vertices. There is also a constant s which is at most the cardinality of a maximum matching in the graph. The goal is to find a minimum-cost matching of size exactly s. The most common case is the case in which the graph admits a one-sided-perfect matching (i.e., a matching of size r), and s=r.

Unbalanced assignment can be reduced to a balanced assignment. The naive reduction is to add ${\displaystyle n-r}$  new vertices to the smaller part and connect them to the larger part using edges of cost 0. However, this requires ${\displaystyle n(n-r)}$  new edges. A more efficient reduction is called the doubling technique. Here, a new graph G' is built from two copies of the original graph G: a forward copy Gf and a backward copy Gb. The backward copy is "flipped", so that, in each side of G', there are now n+r vertices. Between the copies, we need to add two kinds of linking edges:[1]: 4–6

• Large-to-large: from each vertex in the larger part of Gf, add a zero-cost edge to the corresponding vertex in Gb.
• Small-to-small: if the original graph does not have a one-sided-perfect matching, then from each vertex in the smaller part of Gf, add a very-high-cost edge to the corresponding vertex in Gb.

All in all, at most ${\displaystyle n+r}$  new edges are required. The resulting graph always has a perfect matching of size ${\displaystyle n+r}$ . A minimum-cost perfect matching in this graph must consist of minimum-cost maximum-cardinality matchings in Gf and Gb. The main problem with this doubling technique is that there is no speed gain when ${\displaystyle r\ll n}$ .

Instead of using reduction, the unbalanced assignment problem can be solved by directly generalizing existing algorithms for balanced assignment. The Hungarian algorithm can be generalized to solve the problem in ${\displaystyle O(ms+s^{2}\log r)}$  strongly-polynomial time. In particular, if s=r then the runtime is ${\displaystyle O(mr+r^{2}\log r)}$ . If the weights are integers, then Thorup's method can be used to get a runtime of ${\displaystyle O(ms+s^{2}\log \log r)}$ .[1]: 6

### Solution by linear programming

The assignment problem can be solved by presenting it as a linear program. For convenience we will present the maximization problem. Each edge (i,j), where i is in A and j is in T, has a weight ${\textstyle w_{ij}}$ . For each edge ${\displaystyle (i,j)}$  we have a variable ${\textstyle x_{ij}}$ . The variable is 1 if the edge is contained in the matching and 0 otherwise, so we set the domain constraints:

${\displaystyle 0\leq x_{ij}\leq 1{\text{ for }}i,j\in A,T,\,}$

${\displaystyle x_{ij}\in \mathbb {Z} {\text{ for }}i,j\in A,T.}$

The total weight of the matching is: ${\displaystyle \sum _{(i,j)\in A\times T}w_{ij}x_{ij}}$ . The goal is to find a maximum-weight perfect matching.

To guarantee that the variables indeed represent a perfect matching, we add constraints saying that each vertex is adjacent to exactly one edge in the matching, i.e.,

${\displaystyle \sum _{j\in T}x_{ij}=1{\text{ for }}i\in A,\,~~~\sum _{i\in A}x_{ij}=1{\text{ for }}j\in T,\,}$

.

All in all we have the following LP:

${\displaystyle {\text{maximize}}~~\sum _{(i,j)\in A\times T}w_{ij}x_{ij}}$

${\displaystyle {\text{subject to}}~~\sum _{j\in T}x_{ij}=1{\text{ for }}i\in A,\,~~~\sum _{i\in A}x_{ij}=1{\text{ for }}j\in T}$

${\displaystyle 0\leq x_{ij}\leq 1{\text{ for }}i,j\in A,T,\,}$

${\displaystyle x_{ij}\in \mathbb {Z} {\text{ for }}i,j\in A,T.}$

This is an integer linear program. However, we can solve it without the integrality constraints (i.e., drop the last constraint), using standard methods for solving continuous linear programs. While this formulation allows also fractional variable values, in this special case, the LP always has an optimal solution where the variables take integer values. This is because the constraint matrix of the fractional LP is totally unimodular – it satisfies the four conditions of Hoffman and Gale.

### Other methods and approximation algorithms

Other approaches for the assignment problem exist and are reviewed by Duan and Pettie[9] (see Table II). Their work proposes an approximation algorithm for the assignment problem (and the more general maximum weight matching problem), which runs in linear time for any fixed error bound.

## Generalization

When phrased as a graph theory problem, the assignment problem can be extended from bipartite graphs to arbitrary graphs. The corresponding problem, of finding a matching in a weighted graph where the sum of weights is maximized, is called the maximum weight matching problem.

Another generalization of the assignment problem is extending the number of sets to be matched from two to many. So that rather than matching agents to tasks, the problem is extended to matching agents to tasks to time intervals to locations. This results in Multidimensional assignment problem (MAP).


text:
# The European Physical Journal C

## List of Papers (Total 3,037)

#### Ambitwistor superstring in the Green–Schwarz formulation

In this paper we construct the ambitwistor superstring in the Green–Schwarz formulation. The model is obtained from the related pure spinor version. We show that the spectrum contains only ten-dimensional supergravity and that kappa symmetry in a curved background implies some of the standard constraints.

#### Observational properties of rigidly rotating dust configurations

We study the observational properties of a class of exact solutions of Einstein’s field equations describing stationary, axially symmetric, rigidly rotating dust (i.e. non-interacting particles). We ask the question whether such solutions can describe astrophysical rotating dark matter clouds near the center of galaxies and we probe the possibility that they may constitute an ...

#### A chiral covariant approach to $\varvec{\rho \rho }$ scattering

We analyze vector meson–vector meson scattering in a unitarized chiral theory based on a chiral covariant framework restricted to $\rho \rho$ intermediate states. We show that a pole assigned to the scalar meson $f_0(1370)$ can be dynamically generated from the $\rho \rho$ interaction, while this is not the case for the tensor meson $f_2(1270)$ as found in earlier work. ...

#### Anisotropic SD2 brane: accelerating cosmology and Kasner-like space-time from compactification

Starting from an anisotropic (in all directions including the time direction of the brane) non-SUSY D2 brane solution of type IIA string theory we construct an anisotropic space-like D2 brane (or SD2 brane, for short) solution by the standard trick of a double Wick rotation. This solution is characterized by five independent parameters. We show that compactification on ...

#### Warm inflation with an oscillatory inflaton in the non-minimal kinetic coupling model

In the cold inflation scenario, the slow roll inflation and reheating via coherent rapid oscillation, are usually considered as two distinct eras. When the slow roll ends, a rapid oscillation phase begins and the inflaton decays to relativistic particles reheating the Universe. In another model dubbed warm inflation, the rapid oscillation phase is suppressed, and we are left with ...

#### The K-meson form factor and charge radius: linking low-energy data to future Jefferson Laboratory measurements

Starting from a successful model of the $\pi$-meson electromagnetic form factor, we calculate a similar form factor, $F_{K}(Q^{2})$, of the charged K meson for a wide range of the momentum transfer squared, $Q^{2}$. The only remaining free parameter is to be determined from the measurements of the K-meson charge radius, $r_{K}$. We fit this single parameter to the ...

#### Integrability from point symmetries in a family of cosmological Horndeski Lagrangians

For a family of Horndeski theories, formulated in terms of a generalized Galileon model, we study the integrability of the field equations in a Friedmann–Lemaître–Robertson–Walker space-time. We are interested in point transformations which leave invariant the field equations. Noether’s theorem is applied to determine the conservation laws for a family of models that belong to the ...

#### Dark matter phenomenology of SM and enlarged Higgs sectors extended with vector-like leptons

We will investigate the scenario in which the Standard Model (SM) Higgs sector and its two-doublet extension (called the Two Higgs Doublet Model or 2HDM) are the “portal” for the interactions between the Standard Model and a fermionic Dark Matter (DM) candidate. The latter is the lightest stable neutral particle of a family of vector-like leptons (VLLs). We will provide an ...

#### Heavy-quark form factors in the large $\beta _0$ limit

Heavy-quark form factors are calculated at $\beta _0 \alpha _s \sim 1$ to all orders in $\alpha _s$ at the first order in $1/\beta _0$. Using the inversion relation generalized to vertex functions, we reduce the massive on-shell Feynman integral to the HQET one. This HQET vertex integral can be expressed via a ${}_2F_1$ function; the nth term of its $\varepsilon$ ...

#### Exotic Higgs decay $h\rightarrow \phi \phi \rightarrow 4b$ at the LHeC

We study the exotic decay of the 125 GeV Higgs boson (h) into a pair of light spin-0 particles ($\phi$) which subsequently decay and result in a 4b final state. This channel is well motivated in models with an extended Higgs sector. Instead of searching at the Large Hadron Collider (LHC) and the high luminosity LHC (HL-LHC) which are beset by large standard model (SM) ...

#### Tachyon logamediate inflation on the brane

According to a Barrow solution for the scale factor of the universe, the main properties of the tachyon inflation model in the framework of the RSII braneworld are studied. Within this framework the basic slow-roll parameters are calculated analytically. We compare this inflationary scenario to the latest observational data. The predicted spectral index and the tensor-to-scalar ...

#### Excited scalar and pseudoscalar mesons in the extended linear sigma model

We present an in-depth study of masses and decays of excited scalar and pseudoscalar ${\bar{q}}q$ states in the Extended Linear Sigma Model (eLSM). The model also contains ground-state scalar, pseudoscalar, vector and axial-vector mesons. The main objective is to study the consequences of the hypothesis that the $f_0(1790)$ resonance, observed a decade ago by the BES ...

#### Rainbows without unicorns: metric structures in theories with modified dispersion relations

Rainbow metrics are a widely used approach to the metric formalism for theories with modified dispersion relations. They have had a huge success in the quantum gravity phenomenology literature, since they allow one to introduce momentum-dependent space-time metrics into the description of systems with a modified dispersion relation. In this paper, we introduce the reader to some ...

#### Chiral dynamics, S-wave contributions and angular analysis in $D\rightarrow \pi \pi \ell \bar{\nu }$

We present a theoretical analysis of the $D^-\rightarrow \pi ^+\pi ^- \ell \bar{\nu }$ and $\bar{D}^0\rightarrow \pi ^+\pi ^0 \ell \bar{\nu }$ decays. We construct a general angular distribution which can include arbitrary partial waves of $\pi \pi$. Retaining the S-wave and P-wave contributions we study the branching ratios, forward–backward asymmetries and a few other ...

#### Models of collapsing and expanding anisotropic gravitating source in f(R, T) theory of gravity

In this paper, we have formulated the exact solutions of the non-static anisotropic gravitating source in f(R, T) gravity which may lead to expansion and collapse. By assuming there to be no thermal conduction in gravitating source, we have determined parametric solutions in f(R, T) gravity with a non-static spherical geometry filled using an anisotropic fluid. We have examined the ...

#### Higher-dimensional inhomogeneous perfect fluid collapse in f(R) gravity

This paper is about the $n+2$-dimensional gravitational contraction of an inhomogeneous fluid without heat flux in the framework of a f(R) metric theory of gravity. Matching conditions for two regions of a star are derived by using the Darmois junction conditions. For the analytic solution of the equations of motion in modified f(R) theory of gravity, we have taken the scalar ...

#### Higher-twist effects in light-cone sum rule for the $B\rightarrow \pi$ form factor

We calculate the higher-twist corrections to the QCD light-cone sum rule for the $B \rightarrow \pi$ transition form factor. The light-cone expansion of the massive quark propagator in the external gluonic field is extended to include new terms containing the derivatives of the gluon-field strength. The resulting analytical expressions for the twist-5 and twist-6 contributions ...

#### Graviton propagation within the context of the D-material universe

Motivated by the recent breakthrough of the detection of Gravitational Waves (GW) from coalescent black holes by the aLIGO interferometers, we study the propagation of GW in the D-material universe, which we have recently shown to be compatible with large-scale structure and inflationary phenomenology. The medium of D-particles induces an effective mass for the graviton, as a ...

#### Anisotropic Weyl invariance

We consider a non-relativistic free scalar field theory with a type of anisotropic scale invariance in which the number of coordinates “scaling like time” is generically greater than one. We propose the Cartesian product of two curved spaces, the metric of each space being parameterized by the other space, as a notion of curved background to which the theory can be extended. We ...

#### Electroweak monopoles and the electroweak phase transition

We consider an isolated electroweak monopole solution within the Standard Model with a nonlinear Born–Infeld extension of the hypercharge gauge field. Monopole (and dyon) solutions in such an extension are regular and their masses are predicted to be proportional to the Born–Infeld mass parameter. We argue that cosmological production of electroweak monopoles may delay the ...

#### Physical attributes of anisotropic compact stars in f(R, G) gravity

Modified gravity is one of the potential candidates to explain the accelerated expansion of the universe. Current study highlights the materialization of anisotropic compact stars in the context of f(R, G) theory of gravity. In particular, to gain insight in the physical behavior of three stars namely, Her X1, SAX J 1808-3658 and 4U 1820-30, energy density, and radial and ...


text:
## Functions Modeling Change: A Preparation for Calculus, 5th Edition

Though $t$ and $x$ are common variables, there is no requirement that these two letters be the only ones used.