text:
# Brute Force N Body Implementation in C++

I have wrote the following code in C++ for the n-body problem. This code is sequential as later on I am planning to parallelize it using OpenMP. I want to know whether I have wrote the correct implementation, if there are some errors or bugs, or if this is an invalid approach.

#include <iostream>
#include <ctime>
#include <math.h>
using namespace std;
#define N 100
#define G 6.673e-11
#define TIMESTAMP 1e11
struct Particle{
double rx, ry;//position components
double vx, vy;//velocity components
double fx, fy;//force components
double mass;//mass of the particle

};
Particle Update(Particle p, double timestamp)
{
p.vx += timestamp*p.fx / p.mass;
p.vy += timestamp*p.fy / p.mass;
p.rx += timestamp*p.vx;
p.ry += timestamp*p.vy;
return p;
}
void PrintParticle(Particle p)
{
printf("rx == %f ry == %f vx == %f vy == %f mass == %f\n", p.rx,p.ry,p.vx,p.vy,p.mass);
}
//Reset the forces on particle
Particle ResetForce(Particle p)
{
p.fx = 0.0;
p.fy = 0.0;
return p;
}
//Add force to particle a by particle b
{
double EPS = 3E4;      // softening parameter (just to avoid infinities)
double dx = b.rx - a.rx;
double dy = b.ry - a.ry;
double dist = sqrt(dx*dx + dy*dy);
double F = (G * a.mass * b.mass) / (dist*dist + EPS*EPS);
a.fx += F * dx / dist;
a.fy += F * dy / dist;
return a;

}

int main()
{
Particle particles[N];
srand(time(NULL));
//randomly generating N Particles
for (int i = 0; i < N; i++){
double rx = 1e18*exp(-1.8)*(.5 - rand());
particles[i].rx = rx;
double ry = 1e18*exp(-1.8)*(.5 - rand());
particles[i].ry = ry;
double vx = 1e18*exp(-1.8)*(.5 - rand());
particles[i].vx = vx;
double vy = 1e18*exp(-1.8)*(.5 - rand());
particles[i].vy = vy;
double mass = 1.98892e30*rand()*10 + 1e20;
particles[i].mass = mass;

}

int numberofiterations = 10;
int count = 0;
while (count < numberofiterations){
for (int i = 0; i < N; i++)
{
particles[i] = ResetForce(particles[i]);
for (int j = 0; j < N; j++)
{
if (i != j)
{
}

}
}
//loop again to update the time stamp here
for (int i = 0; i < N; i++)
{
particles[i] = Update(particles[i], TIMESTAMP);
}
for (int i = 0; i < N; i++)
{
PrintParticle(particles[i]);
}
count++;
}

return 0;
}

• It's usually a bad idea to create a single-threaded algorithm and then adapt it to multi-threading. Unless you can apply some general pattern (like partitioning the problem space and parallelizing the different partitions), you will probably need something quite different to get performant and safe parallel execution. – Luaan Apr 20 '15 at 9:20
• This is Code Review, so my point is a bit off-topic: You use the explicit Euler method to calculate the next step of your simulation. This is rather unstable and errors accumulate rapidly. You might want to take a look at a Runge-Kutta method. – M.Herzkamp Apr 20 '15 at 13:04
• FYI: here is a nice talk about how to parallelize the n-body problem and this talk uses the n-body problem to demonstrate what you should look out for if you want to speed up your program on a modern processor. – MikeMB Apr 21 '15 at 22:19
• when i run this code it doesn't create an image? – TMC Nov 24 '16 at 11:46

## Make sure to #include all required headers

This program calls printf and srand but does not include the corresponding headers. Fix that by adding these lines:

#include <cstdio>
#include <cstdlib>

## Use objects

You have a Particle structure and then separate functions that operate on Particle data. With only a slight syntax change, you would have a real object instead of C-style code written in C++. For example, you have a loop right now that says this:

for (int i = 0; i < N; i++)
{
particles[i] = Update(particles[i], TIMESTAMP);
}

With objects, and with C++11 or newer, you could instead write this:

for (auto &p : particles)
p.update(TIMESTAMP);

All that would be required would be to make Update a member function.

## Prefer stream I/O to printf

The printf function was a capable workhorse for many years, but the C++ iostream library is better in a number of regards. Although it's often more typing for the programmer initially, it's better because it has better type checking, less possibility for runtime overhead, and it fits well with the rest of C++. So I would probably change your PrintParticle to this:

friend ostream& operator<<(ostream& out, const Particle &p) {
return out <<
"rx == " << p.rx_ <<
" ry == " << p.ry_ <<
" vx == " << p.vx_ <<
" vy == " << p.vy_ <<
" mass == " << p.mass_ << '\n';
}

## Use const where practical

There are a number of things in your code that look and act like constants, such as numberofiterations in main(). Declare them as const for a program more resistant to error. Also, move the constants, such as N into main rather than having them at file scope.

## Create a function rather than repeating code

The functions which create the particle use the same rand()-based function several times. Instead of repeating it, make it into a function:

double xrand() {
return 1e18*exp(-1.8)*(.5 - rand());
}

## Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid. It isn't necessarily wrong to use, but be aware of when you absolutely shouldn't do it (such as in header files).

## Consider using a better random number generator

If you are using a compiler that supports at least C++11, consider using a better random number generator. In particular, instead of rand, you might want to look at std::uniform_real_distribution and friends in the <random> header.

At the moment, the force on each particle from every other particle is calculated exhaustively, but Newton tells us that the force actually acts equally (but opposite) on both particles, so your loop could be simplified and calculations speeded if you take advantage of that fact to only calculate force vectors once and then apply them to both.

## Double check your constant values

It seems to me that 3e4 is a somewhat large value for EPS. Additionally, in the calculation of the random mass, the math is currently 1.98892e30*rand()*10 + 1e20, but why not simply write 1.98892e31*rand() + 1e20 instead?

## Eliminate return 0 at the end of main

When a C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no reason to put return 0; explicitly at the end of main.

• return 0; might be optional but it is confusing that main is the only function in the program that behaves differently in this regard. – usr Apr 19 '15 at 15:35
• It's confusing after 100 years and it has no value leaving it out. – usr Apr 19 '15 at 16:16
• @usr: I use the existance of a return at the end of main to indicate if the application reports errors or not. If your application can and does return alterntive values to indicate error situations then a return value is useful other wise it has no meaning so let the compiler generate the correct code for you. – Martin York Apr 19 '15 at 16:17
• @andrepd: That is a myth (that they are vastly different) and has been covered many times on SO. Just decouple the C++ streams from the C streams std::ios_base::sync_with_stdio(false) and it works as efficiently (slightly slower). see printf more than 5 times faster than std::cout? (Note its not). Also this has been discussed on comp.lang.c++ where the consensus seems to be "be robust". – Martin York Apr 20 '15 at 18:52
• @andrepd: There is not a 25% difference in printf() and iostreams when it comes to printing floats (on my machine I am getting less than 5%). But yes, if you just want to dump floats and there are billions of them fine use printf (but make sure that the number is significant enough that it is worth it). But if you want more functionality then use streams; it provides much more functionality under the hood (localization/translation etc) in addition to type to checking. – Martin York Apr 22 '15 at 16:43

All points by @Edvard are good. Here are a couple more.

## Encapsulation

All your functions mutate a Particle structure. So why not just make this methods on your class?

struct Particle{
double rx, ry;//position components
double vx, vy;//velocity components
double fx, fy;//force components
double mass;//mass of the particle

};
Particle Update(Particle p, double timestamp);
void PrintParticle(Particle p);
Particle ResetForce(Particle p);

I would have written this as:

classe Particle
{
// Members are all private.
// You mutate and access them via methods.
double rx, ry;//position components
double vx, vy;//velocity components
double fx, fy;//force components
double mass;//mass of the particle

public:

Particle(double rx, double ry, double vx, double vy, double fx, double fy, double mass)
:rx(rx) ,ry(ry)
,vx(vx) ,vy(vy)
,fx(fx) ,fy(fy)
,mass(mass)
{}

// If these methods return void or Particle& depends
// on context and usage patterns. I have left then as close
// to the original functions as possible.
Particle& update(double timestamp);
void printParticle(std::ostream& str);
Particle& resetForce();

friend std::ostream& operator<<(std::ostream& str, Particle const& data)
{
printParticle(str);
return str;
}
};

## Don't use macros

#define N 100
#define G 6.673e-11
#define TIMESTAMP 1e11

Macros don't obey scope rules and have no type information (they are simple text substitutions). Prefer to use const variables (or constexpr in C++11);

constexpr int    N         = 100;
constexpr double G         = 6.673e-11;
constexpr double TIMESTAMP = 1e11;

## Prefer Standard containers

Arrays are limited. They don't work well with a lot of other constructs in the language as they quickly degrade into pointers just by looking at them funnily (them people start worrying about memory management).

Particle particles[N];

It is better to use modern constructs like std::vector<> or std::array<> as these object maintain there type information correctly.

std::array<Particle, N>  particles;   // fixed size array of particles.
// useful if you they can be
// build by default contructor

Alternatively:

 std::vector<Particle>   particles;   // Dynamically sized array.
particles.reserve(N);                // Useful when built dynamically
// from a loop as you can call
// the constructor specifically.

## Prefer for(;;) over while() when counter is used

int count = 0;
while (count < numberofiterations){
// STUFF
count++;
}

// Easier to read and reason (as the increment is obvious)
for(int count = 0; count < numberofiterations; ++count) {
// STUFF
}

## Standard algorithms

Look at the standard algorithms and use them when you can. Alternatively use the for() syntax for looping over containers.

## Refactoring the main now looks like this:

int main()
{
srand(time(NULL));

std::vector<Particle> particles;
particles.reserve(N);

//randomly generating N Particles
for (int i = 0; i < N; i++)
{
particles.emplace_back(getRand(), getRand(),
getRand(), getRand(),
getRand(), getRand(),
getRandMass());
}

int constexpr numberofiterations = 10;

for(int count = 0; count < numberofiterations; ++count) {
for (int i = 0; i < N; ++i) {
particles[i].resetForce();
for (int j = 0; j < N; ++j) {
if (i != j) {
}
}
}
//loop again to update the time stamp here
for (auto& particle: particles) {
particle.update(TIMESTAMP);
}
std::copy(std::begin(particles), std::end(particles),
std::istream_iterator<Particle>(std::cout));
}
}

• The rewrite I did looks almost identical to this except that I also made N and TIMESTAMP local to main, and I missed the opportunity to use emplace_back as you have. Nice! – Edward Apr 19 '15 at 19:31
• he seems to want a normal/Gaussian distribution (bell curve), so std::uniform_real_distribution is not ideal -- try std::normal_distribution instead. en.cppreference.com/w/cpp/numeric/random/normal_distribution – Snowbody Apr 20 '15 at 17:37
• @Snowbody: I did not cover random number generation as Edward had already got that one down. But yes; pick an appropriate distribution. – Martin York Apr 20 '15 at 18:40

All the advice from @Edvard and @Loki Astari are good. However, one thing I'd also recommend you on doing is to use dimensionless units. That way you have two advantages:

• It is easier to generalize the system;
• You are less prone to loss of precision.

@Snowbody (fairly) asked if such system as for $G=1$. Yes, but not only. One should set the whole system of units.

Say, if you have the following energy:

$U = G \sum_{ij} \frac{m_i m_j}{r_{ij}}$

You can define dimensionless units as

$m' = m/m_0$;

$r' = r/r_0$;

$U' = U/E_0$.

Thus,

$U' = \frac{U}{E_0} = \frac{G}{E0} \sum_{ij} \frac{m_i m_j}{r_{ij}}$.

Replacing $r$ and $m$ in $U'$.

$U' = \frac{U}{E_0} = \frac{G}{E_0} \sum_{ij} \frac{m_i' m_j' m_0^2}{r_{ij'} r_0}$.

$U' = \frac{G m_0^2}{E_0r_0} \sum_{ij} \frac{m_i' m_j'}{r_{ij}'}$.

Now comes the cool part. We want the first term to unity. So, we say that

$\frac{G m_0^2}{E_0r_0} =1$

or

$\frac{G m_0^2}{r_0} = E_0$

$U' =\sum_{ij} \frac{m_i' m_j'}{r_{ij}}$.

Now one knows how to link the real values with the simulations. Say one wants to simulate the earth-moon. Then $m_0$ can be the mass of the Earth. Then, in the program, $m_{Earth} = 1.0$ and $m_{Moon} = 0.012300$*. One can do the same thing for $r_0$.

* Moon mass in Earth units according to wikipedia

• Could you expand on what you mean by "dimensionless units" or include a link to same? I believe you mean choosing units such that G=1, right? – Snowbody Apr 20 '15 at 16:05
• Yes, but not only. What you want is a whole system without dimension. I'll edit the main part to add that. – rmk236 Apr 21 '15 at 16:48
• why are you storing the force component instead of the acceleration? Do you expect particles' masses to change? Division is usually more expensive than multiplication, so do it as little as possible.
• Why are you calculating distance squared, then square rooting it, then squaring it again? The compiler may be able to optimize this one though.


text:
## Taiwanese Journal of Mathematics

### MAXIMUM PACKINGS AND MINIMUM COVERINGS OF MULTIGRAPHS WITH PATHS AND STARS

#### Abstract

Let $F$, $G$, and $H$ be multigraphs. An $(F,G)$-decomposition of $H$ is an edge decomposition of $H$ into copies of $F$ and $G$ using at least one of each. For subgraphs $L$ and $R$ of $H$, an $(F,G)$-packing of $H$ with leave $L$ is an $(F,G)$-decomposition of $H-E(L)$, and an $(F,G)$-covering of $H$ with padding $R$ is an $(F,G)$-decomposition of $H+E(R)$. A maximum $(F,G)$-packing of $H$ is an $(F,G)$-packing of $H$ with a minimum leave. A minimum $(F,G)$-covering of $H$ is an $(F,G)$-covering of $H$ with a minimum padding.  Let $k$ be a positive integer. A $k$-path, denoted by $P_k$, is a path on $k$ vertices. A $k$-star, denoted by $S_k$, is a star with $k$ edges. In this paper, we obtain a maximum $(P_{k+1},S_{k})$-packing of $\lambda K_n$, which has a leave of size $\lt k$, and a minimum $(P_{k+1},S_{k})$-covering of $\lambda K_n$, which has a padding of size $\lt k$. A similar result for $\lambda K_{n,n}$ is also obtained. As corollaries, necessary and sufficient conditions for the existence of $(P_{k+1},S_k)$-decompositions of both $\lambda K_n$ and $\lambda K_{n,n}$ are given.

#### Article information

Source
Taiwanese J. Math., Volume 19, Number 5 (2015), 1341-1357.

Dates
First available in Project Euclid: 4 July 2017

Permanent link to this document
https://projecteuclid.org/euclid.twjm/1499133712

Digital Object Identifier
doi:10.11650/tjm.19.2015.4456

Mathematical Reviews number (MathSciNet)
MR3412009

Zentralblatt MATH identifier
1357.05124

Keywords
packing covering path star

#### Citation

Lee, Hung-Chih; Chen, Zhen-Chun. MAXIMUM PACKINGS AND MINIMUM COVERINGS OF MULTIGRAPHS WITH PATHS AND STARS. Taiwanese J. Math. 19 (2015), no. 5, 1341--1357. doi:10.11650/tjm.19.2015.4456. https://projecteuclid.org/euclid.twjm/1499133712

#### References

• A. Abueida, S. Clark, and D. Leach, Multidecomposition of the complete graph into graph pairs of order 4 with various leaves, Ars Combin., 93 (2009), 403-407.
• A. Abueida and M. Daven, Multidesigns for graph-pairs of order 4 and 5, Graphs Combin., 19 (2003), 433-447.
• A. Abueida and M. Daven, Multidecompositons of the complete graph, Ars Combin., 72 (2004), 17-22.
• A. Abueida and M. Daven, Multidecompositions of several graph products, Graphs Combin., 29 (2013), 315-326.
• A. Abueida, M. Daven, and K. J. Roblee, Multidesigns of the $\lambda$-fold complete graph for graph-pairs of order 4 and 5, Australas J. Combin., 32 (2005), 125-136.
• A. Abueida and C. Hampson, Multidecomposition of $K_n-F$ into graph-pairs of order 5 where $F$ is a Hamilton cycle or an (almost) 1-factor, Ars Combin., 97 (2010), 399-416
• A. Abueida and T. O'Neil, Multidecomposition of $\lambda K_m$ into small cycles and claws, Bull. Inst. Combin. Appl., 49 (2007), 32-40.
• J. Bosák, Decompositions of Graphs, Kluwer, Dordrecht, Netherlands, 1990.
• Darryn Bryant, Packing paths in complete graphs, J. Combin. Theory Ser. B 100 (2010), 206-215.
• P. Hell and A. Rosa, Graph decompositions, handcuffed prisoners and balanced $P$-designs, Discrete Math., 2 (1972), 229-252.
• D.G. Hoffman, The real truth about star designs, Discrete Math., 284 (2004), 177-180.
• H.-C. Lee, Multidecompositions of complete bipartite graphs into cycles and stars, Ars Combin., 108 (2013), 355-364.
• H.-C. Lee and J.-J. Lin, Decomposition of the complete bipartite graph with a $1$-factor removed into cycles and stars, Discrete Math., 313 (2013), 2354-2358.
• J.-J. Lin, Decompositions of multicrowns into cycles and stars, Taiwanese J. Mathematics, accepted.
• C. A. Parker, Complete bipartite graph path decompositions, Ph.D. Thesis, Auburn University, Auburn, Alabama, 1998.
• H. M. Priyadharsini and A. Muthusamy, $(G_m,H_m)$-multifactorization of $\lambda K_m$, J. Combin. Math. Combin. Comput., 69 (2009), 145-150.
• H. M. Priyadharsini and A. Muthusamy, $(G_m,H_m)$-multidecomposition of $K_{m,m}(\lambda)$, Bull. Inst. Combin. Appl., 66 (2012), 42-48.
• T.-W. Shyu, Decomposition of complete graphs into paths and stars, Discrete Math., 310 (2010), 2164-2169.
• T.-W. Shyu, Decompositions of complete graphs into paths and cycles, Ars Combin., 97 (2010), 257-270.
• T.-W. Shyu, Decomposition of complete graphs into paths of length three and triangles, Ars Combin., 107 (2012), 209-224.
• T.-W. Shyu, Decomposition of complete graphs into cycles and stars, Graphs Combin., 29 (2013), 301-313.
• T.-W. Shyu, Decomposition of complete bipartite graphs into paths and stars with same number of edges, Discrete Math., 313 (2013), 865-871.

format: plain


text:
An investor purchased 20 shares of a certain stock at a price of $45.75 per share. Later this investor purchased 30 more shares at a price of$46.25 per share. What was the average (arithmetic mean) price per share that this investor paid for the 50 shares?

$45.80$45.95

$46.00$46.05

\$46.20


text:
As promised in the previous post, here is a little writeup of the second conference I was at recently…

Connections in Geometry and Physics

The conference at PI was an interestingly varied cross-section of talks, with a good many of them about geometry which, to be honest, is a little over my head.  Ostensibly about “connections”, the talks actually ranged quite widely, which was interesting, and reminded me I have a lot af geometry to catch up on.  A lot of talks had to do with structures at various places along the heirarchy: (1) symplectic manifolds, (2) Kähler manifolds, and (3) Calabi-Yau manifolds.  These last are interesting to string theorists and others, in part because they satisfy a form of Einstein’s equations, while also carrying a bunch of extra structure.

Now, at least I know what all the above things are: Symplectic manifolds $(M,\omega)$ have the “symplectic form” $\omega$, a non-degenerate exact 2-form (a canonical example being $\sum dp^i \wedge dq^i$ in the cotangent space to $\mathbb{R}^n$, which happens to be the configuration space for a particle moving in $\mathbb{R}^n$ – symplectic forms often show up on configuration spaces).  A Kähler manifold is symplectic, but also has a complex structure (i.e. a way to multiply tangent vectors by $i$), which preserves the symplectic form, and a metric, which gets along with both of the above.  If the metric satisfies Einstein’s equations and is flat (this really amounts to the connection to “connections”, since this is the same as there being some flat connections, namely the Levi-Civita connection), then $M$ is a Calabi-Yau manifold.

Anyway, this sets up the kind of geometry a lot of people were talking about, and while I didn’t exactly have the background to follow everything, I got a sense of what kinds of questions people are interested in, which was good.  A lot of questions have to do with Lagrangian submanifolds of any of the above (from symplectic through Calabi-Yau).  These are submanifolds where the symplectic form gives zero when applied to any tangent, and which have the highest possible dimension consistent with this property (namely $n$, if the original thing is $2n$-dimensional).  Another theme which came up several times – for example, in the talk by Denis Auroux – has to do with “mirror symmetry” for Kähler manifolds (and Calabi-Yaus), which has to do with finding a “mirror” for the manifold $M$, called $\check{M}$ where the complex geometry on the mirror corresponds to the symplectic geometry on $M$, and vice versa.

There were some talks in the direction of physics.  One of the most obviously physical was Niky Kamran’s, talking about a project he’s worked on with F. Finster, J. Smoller, and S-T. Yau, about long-time dynamics of particles satisfying the Dirac equation, living on a background geometry described by the Kerr metric – which describes a rotating black hole.  Since I worked with Niky on a related project for my M.Sc (my thesis was basically a summary putting together a bunch of results by these same four people), I followed this talk better than many of the others.

Working on this project, I got a strong sense of how important symmetry is in studying a lot of real-world problems.  One of the essential facts about the Kerr metric is that it’s very symmetric: it’s stable in time, and rotationally symmetric.  Actually, all the black-hole solutions to Einstein’s equations are quite symmetric – there is only a small family of solutions, parametrized by mass and angular momentum (and electrical charge).  The symmetry makes differential equations written in terms of this metric much nicer – you can split things into the radial and angular parts, for example – and in particular, the wave equations Niky was talking about are integrable just because of this symmetry, so it’s possible to get exact analytic results.  (Other approaches to this kind of problem get results only numerically and approximately, but can deal with much more general backgrounds.)  The starting point (which basically is what my thesis summarizes) is to show that there are no “bound states” for the Dirac equation.  Fermions (which is what it describes) are most familiar to us in bound states: in shells orbiting the nucleus of an atom.  But if the attractive force pulling on them is gravity, rather than electical charge, this situation isn’t stable.  The work Niky was talking about deals with what happens instead: what are the long-term dynamics of a fermion near a rotating black hole?

They use spectral methods – basically, Fourier analysis – to find out.  The Dirac equation is a wave equation (for a spinor field), and you can look at the different frequencies, and get an estimate of how fast they decay.  (Since there aren’t stable orbits, the strength of the spinor field has to decay over time.)  In fact, they get a sharp estimate of the order (namely $t^{-5/6}$).  Basically, one should imagine that the wave is a superposition of “ripples” – some radiating outward from the event horizon, and some converging toward it.  Put in terms of a particle – an electron, say, or a neutrino – this says it will either fall into the black hole, or (if it has enough energy) escape off to infinity.

There were some other physics-ish talks, such as that by James Sparks, on the geometry of the “AdS/CFT” correspondence.  This correspondence has to do with two kinds of quantum field theory.  The “AdS” stands for “Anti de Sitter”, which is a sort of geometric structure for a manifold which resembles a hyperboloid – actually, all the unit vectors in $\mathbb{R}^6$ where the metric has signature (4,2): that is, the metric is something like $\Delta(1,1,1,1,-1,-1)$.  This hyperboloid is 5-dimensional, and has a metric with one timelike dimension.  Plain old “de Sitter” space is a similar thing, but using a metric with signature (5,1).  It’s possible to define some field theory on AdS space, called supersymmetric supergravity.  This theory turns out to have exactly the same algebra of observables as a different theory, “CFT” or conformal field theory, on the (conformal) boundary of Anti de Sitter space.  Sparks told us about a geometric interpretation of this.

Then there was Sergei Gukov, with a talk called “Brane Quantization”, based on this work with Ed Witten.  He was a little reticent to actually describe how this “brane quantization” actually works, preferring to refer us to that paper, but gave us a very nice, and relatively comprehensible overview of different approaches to quantizing a symplectic manifold.  (As I said, they tend to show up as configuration spaces in classical physics. A basic problem of quantization is how to turn the algebra of functions on a symplectic manifold $(M,\omega)$ into an algebra of operators on a Hilbert space $\mathcal{H}$.)  In particular, he contrasted their method with geometric quantization (which needs to make some arbitrary choices, then takes $\mathcal{H}$ to be a space of sections of some line bundle on $M$ with a connection whose curvature is $\omega$), and with deformation quantization (which needs no special choices, but only constructs an algebra of operators by algebraic deformation, and not actually $\mathcal{H}$ itself, which some people, but not Sergei Gukov, find satisfactory).  The basic idea of Brane quantization seems to be that $M$ gets complexified (somehow – it might be either impossible, or non-unique), and then studying something called an A-model of the result.  This is apparently related to, for example, Gromov-Witten theory, which I’ve written about here recently.

Finally, I’ll mention a few other talks which stood out as rather different from the rest.  Veronique Godin talked about “Relative String Topology” – string topology being a way of studying space by looking at embeddings of the circle (or of paths) into it – that is, its loop space (or path space).  Usually, invariants that come from path spaces only detect the homotopy type of the original spaces – in particular, they’re not helpful as knot invariants.  Godin talked about a clever way to detect more structure by means of an $A_{\infty}$-coalgebra structure on the cohomology groups of the path space.  The “relative” part means one’s looking at a manifold $M$ with embedded submanifold $N$ (for example, $N$ is a knot in $M=\mathbb{R}^3$), and considering only paths starting and ending on $N$.  (This is how one can get a coalgebra structure – turning one path into two paths if it crosses through $N$ again is a comultiplication – this extends to chains in the cohomology).

Chris Brav gave a talk about how braid groups act on derived categories, which I didn’t entirely follow, but subsequently he did explain to me in a pretty comprehensible way what people are trying to accomplish when they look at derived categories.  At some point I’ll have to think about this more carefully and maybe post about it.  But roughly, it’s the same sort of “nice categorical properties” I mentioned in the previous post, about smooth spaces.  Looking at derived categories of sheaves on a space, makes the objects seem more complicated, but it also makes them behave better with respect to taking things like limits and colimits.

Benjamin Young prefaced his talk, “Combinatorics Inspired by Donaldson-Thomas Theory” by pointing out that he’s a combinatorialist, not a geometer.  But Donaldson-Thomas invariants are apparently a kind of “signed count” of some geometric structures (as are a lot of invariants – the same kind of “weighted count” invariants appear in Gromov-Witten and Dijkgraaf-Witten theory, just for instance).  So he described some geometry relating to “brane tilings” – basically, embedding certain kinds of graphis in a torus – and how they give rise to structures that correspond to certain kinds of Young diagrams (“not the same Young”, he added, perhaps unnecessarily, but it got a chuckle anyway).  So the counts can be turned into a combinatorial problem of counting those Young diagrams with the appropriate sign, which can be done using a generating function.

So in any case, this conference had a whole range of talks, from several different fields.  While I found myself lost in a number of talks, I was also quite fascinating with how wide a range of topics were embraced under its umbrella – “connections” indeed!  So in the end this was one of those conferences which opened my eyes to a wider view of the field, which was certainly a good reason to go!


text:
# Dividing by Multiples of Negative Powers of Ten (E): Single-Digit Facts

##### This Dividing by Multiples of Negative Powers of Ten (E): Single-Digit Facts worksheet also includes:

In this dividing by multiples of negative powers of ten learning exercise, students are given 10 numbers which they are to divide by a given set of numbers which are formatted x, .x, .0x, .00x and .000x.

Concepts

Resource Details


text:
# Convolutional Neural Networks layer sizes

I am trying to understand an article Backpropagation In Convolutional Neural Networks

But I can not wrap my head around that diagram:

The first layer has 3 feature maps with dimensions 32x32. The second layer has 32 feature maps with dimensions 18x18. How is that even possible ? If a convolution with a kernel 5x5 applied for 32x32 input, the dimension of the output should be $(32-5+1)$ by $(32-5+1)$ = $28$ by $28$.

Also, if the first layer has only 3 feature maps, the second layer should have multiple of 3 feature maps, but 32 is not multiple of 3.

Also, why is the size of the third layer is 10x10 ? Should it be 9x9 instead ? The dimension of the previouse layer is 18x18, so 2x2 max pooling should reduce it to 9x9, not 10x10.

• Your observation is correct and it seems that the author has mistyped some values.. – Aditya Feb 27 '18 at 6:46
• Just checking, is there any mention of padding? Padding would make feature map reduction a bit less intuitive!! Oveal, you are right the size convention here seems rather confusing. For example, "3 feature maps with dimensions 32x32", do you mean a 32x32 color image then (32x32x3), and three is the channel! Check the excellent book by Ian Goodfellow book freely available online: deeplearningbook.org – TwinPenguins Feb 27 '18 at 8:05

Actually I guess you are making mistake about the second part. The point is that in CNNs, convolution operation is done over volume. Suppose the input image is in three channels and the next layer has 5 kernels, consequently the next layer will have five feature maps but the convolution operation consists of convolution over volume which has this property: each kernel will have its width and height, moreover, a depth. its depth is equal to the number of feature maps, here channels of the image, of the previous layer. Take a look at here.


text:
# Horizontal placement of graphic in left and right margins

I want to place small graphics in the outer margins of my 2-sided document. I've been using, e.g.,

\marginpar[{\hfill
\includegraphics[scale=.3]{figures/ivy-univ.png}\hspace{8 pt}
}]{
\includegraphics[scale=.3]{figures/ivy-univ.png}
}

It works fine on the right-hand page margins, but the graphic overlaps the text on the left-hand pages. I've been playing with the \hfill, \hspace and with using \marginnote, but can't get it right. \marginnote got the position right, but didn't recognize left vs right page properly. Any help is appreciated.

• Welcome to TeX.SX! You can have a look at our starter guide to familiarize yourself further with our format. – Heiko Oberdiek May 5 '14 at 21:13
• Do you get overfull \hbox warnings? Maybe the graphics is too large for the margin? – Heiko Oberdiek May 5 '14 at 21:15
• use width=\marginparparwidth rather than scale=.3 then it will not be too large for the space – David Carlisle May 5 '14 at 21:33


text:
# 27.1: The Average Translational Kinetic Energy of a Gas

### Equipartitioning of Energy

When the mechanical energy is

$\mathcal{E}(x) = \mathcal{H}(x) = \sum_{i=1}^N \dfrac{\textbf{p}_i^2}{2m_i} + U \left( \textbf{r}_1, \ldots, \textbf{r}_N \right) \label{1}$

the canonical distribution function nicely separates into a product of momentum and coordinate distributions:

\begin{align} f(x) &= \dfrac{C_N}{Q(N, V, T)} \left[ e^{-\beta \sum_{i=1}^N \textbf{p}_i^2/2m_i} \right] \left[ e^{-\beta U \left( \textbf{r}_1, \ldots, \textbf{r}_N \right)} \right] \\ &= \dfrac{C_N}{Q(N, V, T)} \left[ \prod_{i=1}^N e^{-\beta \textbf{p}_i^2/2m_i} \right] \left[ e^{-\beta U \left( \textbf{r}_1, \ldots, \textbf{r}_N \right)} \right] \\ &= \left[ \prod_{i=1}^N P \left( \textbf{p}_i \right) \right] \left[ \dfrac{1}{Z} \: e^{-\beta U \left( \textbf{r}_1, \ldots, \textbf{r}_N \right)} \right] \\ &= \left[ \prod_{i=1}^N \mathcal{P} \left( p_{x, i} \right) \: \mathcal{P} \left( p_{y, i} \right) \: \mathcal{P} \left(p_{z, i} \right) \right] \left[ \dfrac{1}{Z} \: e^{-\beta U \left( \textbf{r}_1, \ldots, \textbf{r}_N \right)} \right] \end{align} \label{2}

where $$P \left( \textbf{p}_i \right)$$ is the Maxwell-Boltzmann distribution as a function of the momentum $$\textbf{p}_i$$.

Given this decomposition of the momentum distribution into products of distributions of individual components, we always have, for any system,

$\left< \sum_{i=1}^N \dfrac{\textbf{p}_i^2}{2m_i} \right> = \dfrac{3}{2} N k_B T \label{3}$

However, in addition to this, we also have the following averages:

$\left< \dfrac{\textbf{p}_i^2}{2m_i} \right> = \dfrac{3}{2} k_B T \label{4}$

and

$\left< \dfrac{p_{x, i}^2}{2m_i} \right> = \dfrac{1}{2} k_B T, \: \: \: \left< \dfrac{p_{y, i}^2}{2m_i} \right> = \dfrac{1}{2} k_B T, \: \: \: \left< \dfrac{p_{z, i}^2}{2m_i} \right> = \dfrac{1}{2} k_B T \label{5}$

The fact that these averages can be written for every individual component tells us that each degree of freedom has an average of $$k_B T/2$$ energy associated with it. This is called equipartitioning of energy.

How does equipartitioning happen? It occurs through the interactions in the system, which dynamically, produce collisions, leading to covalent bond breaking and forming events, hydrogen bond breaking and forming events, halogen bond breaking and forming events, diffusion, and so forth, all depending on the chemical composition of the system. Each individual collision event leads to a transfer of energy from one particle to another, so that, on average, all particles have the same energy $$k_B T/2$$. This does not mean that, at any instant, this is the energy of a randomly chosen particle. Obviously, there are considerable fluctuations in the energy of any one particle, however, the average over these fluctuations must produce the value $$k_B T/2$$.

A system obeys a well defined set of classical equations of motion, so that we can, in principle, determine exactly when the next collision will occur and exactly how much energy will be transferred in the collision. However, since we do not follow the detailed motion of all of the particles, our description of collisions and their consequences must be statistical in nature. We begin by defining a few simple terms that are commonly used for this subject.


text:
Lemma 15.95.8. Let $A$ be a ring and let $f \in A$ be a nonzerodivisor. Let $M^\bullet$ be a complex of $f$-torsion free $A$-modules. If $\mathop{\mathrm{Ker}}(d^ i \bmod f^2)$ surjects onto $\mathop{\mathrm{Ker}}(d^ i \bmod f)$, then the canonical map

$(1, d^ i) : (\eta _ fM)^ i / f(\eta _ fM)^ i \longrightarrow f^ iM^ i/f^{i + 1}M^ i \oplus f^{i + 1}M^{i + 1}/f^{i + 2}M^{i + 1}$

identifies the left hand side with a direct sum of submodules of the right hand side.

Proof. With notation as in Remark 15.95.5 we define a map $t^{-1} : Z^ i \to (\eta _ fM)^ i / f(\eta _ fM)^ i$. Namely, for $x \in M^ i$ with $d^ i(x) = f^2y$ we send the class of $x$ in $Z^ i$ to the class of $f^ ix$ in $(\eta _ fM)^ i / f(\eta _ fM)^ i$. We omit the verification that this is well defined; the assumption of the lemma exactly signifies that the domain of this operation is all of $Z^ i$. Then $t \circ t^{-1} = \text{id}_{Z^ i}$. Hence $t^{-1}$ defines a splitting of the short exact sequence in Remark 15.95.5 and the resulting direct sum decomposition

$(\eta _ fM)^ i / f(\eta _ fM)^ i = Z^ i \oplus B^{i + 1}$

is compatible with the map displayed in the lemma. $\square$

There are also:

• 2 comment(s) on Section 15.95: An operator introduced by Berthelot and Ogus

In your comment you can use Markdown and LaTeX style mathematics (enclose it like $\pi$). A preview option is available if you wish to see how it works out (just click on the eye in the toolbar).


text:
# PHP/MySQL to delete data from 4 different tables at once

I have four mysql tables setup like the following:

users (userid, firstname, lastname)  *one entry per user
schedules (userid, scheduleid, schedulename) *each user could have multiple schedules
classes (classid, scheduleid, classname) *each schedule is made up of multiple classes
schools (scheduleid, schoolid, schoolname) *one entry per user

I want the user to be able to delete their account, including ANY info from other tables tied to their account. So if they had 3 schedules with a bunch of classes in each and a school tied to each schedule, I'd want ALL of that data (including their user info) to be deleted in one fell swoop.

userid is all I need to delete from the users and schedules table easily. But the classes and schools tables DON'T have a userid field, so I have to do some other way.

I wrote and tested the following code and it works fine...

//first get all schedules associated with this user account and put scheduleids into array
$sql = "SELECT scheduleid FROM schedules WHERE userid = '$userid'";
$selectschedules = mysqli_query($connection, $sql); if (!$selectschedules) {
die("Database query failed: " . mysqli_error());
} else {
while($data=mysqli_fetch_assoc($selectschedules)){
$schedules[] =$data;
}
}
//now loop through each schedule to delete all classes and any school associated with that particular schedule
foreach ($schedules as$item) {
$sql = "DELETE FROM classes WHERE scheduleid = '".$item['scheduleid']."'";
$deleteclasses = mysqli_query($connection, $sql); if (!$deleteclasses) {
die("Database query failed: " . mysqli_error());
} else {
}
$sql = "DELETE FROM schools WHERE scheduleid = '".$item['scheduleid']."'";
$deleteschool = mysqli_query($connection, $sql); if (!$deleteschool) {
die("Database query failed: " . mysqli_error());
} else {
}
}
//next delete all schedules associated with user account
$sql = "DELETE FROM schedules WHERE userid = '$userid'";
$deleteschedules = mysqli_query($connection, $sql); if (!$deleteschedules) {
die("Database query failed: " . mysqli_error());
} else {
}
//finally, delete the user's account
$sql = "DELETE FROM users WHERE userid = '$userid'
LIMIT 1"; //should only be one, just being safe
$deleteuser = mysqli_query($connection, $sql); if (!$deleteuser) {
die("Database query failed: " . mysqli_error());
} else {
}

However, I believe the above code is inefficient (particularly looping through each schedule and doing delete queries on every loop). So I'm curious if there is a shorter/more efficient way to accomplish this same thing. I am not good with JOINS and could be wrong, but would using JOINS potentially be the key to shortening this and NOT having to loop at all?

SIDE NOTE: Earlier I mentioned that classes and schools tables DON'T have a userid field. If they did, it would be very easy to delete all of this stuff in one query. So it begs the question: Should I add the userid field to the other tables? I don't want to add it just to make deleting easier, but if you think it SHOULD have it regardless, then I would consider.

Any info/suggestions would be greatly appreciated.

Basically there are three vectors of improvement:

• of course you can make your queries optimal, avoiding a loop
• also, I would suggest to optimize the the process of executing the query, as it is evident that each query takes too much code to write
• you should never put a single variable directly in the query, but always use a prepared statement instead.

To solve the first problem, you can always use a JOIN. Yes, DELETE queries support JOINs as well as SELECT ones. So it goes:

DELETE c.* FROM classes c, schedules s WHERE c.scheduleid=s.id AND s.userid = ?

To solve the second one would propose to use PDO (which can solve the third one as well) as it lets you to run a query in one line:

$pdo->prepare("DELETE FROM users WHERE userid = ?")->execute([$userid]);

So the overall code would be

$sql = "DELETE c.* FROM classes c, schedules s WHERE c.scheduleid=s.scheduleid AND s.userid = ?";$pdo->prepare($sql)->execute([$userid]);

$sql = "DELETE c.* FROM schools sc, schedules s WHERE sc.scheduleid=s.scheduleid AND s.userid = ?";$pdo->prepare($sql)->execute([$userid]);

$sql = "DELETE FROM schedules WHERE s.userid = ?";$pdo->prepare($sql)->execute([$userid]);

$sql = "DELETE FROM users WHERE s.userid = ?";$pdo->prepare($sql)->execute([$userid]);

As long as you are connecting to PDO properly, this code will report errors automatically, without a single extra line of code!

Should I add the userid field to the other tables?

Quite contrary, you should NOT add such a field, keeping your database structure as normalized as possible

• This looks like great info thank you. Ill definitely look into PDO. I have a ton of existing queries, sounds like you're saying it would be worth the time to go back and change all of them to use PDO? Finally, your way is much less code, but I'm just curious, there is still no way to delete everything from all four tables in literally ONE query using JOINs? I'm guessing you gave it to me as succint as it can be, just curious. Thx! – user3304303 May 19 '17 at 14:48
• I think yes, you can delete with a single query, but I never tried it myself. But it is supported - you just add the table alias after delete, like DELETE c, sc, u FROM .... You can experiment yourself and then post an answer! – Your Common Sense May 19 '17 at 14:58
• I should have mentioned a cascade delete also. Actually you can set foreign keys in mysql and only delete from user - the rest mysql will do by itself. Refer here: mysqltutorial.org/mysql-on-delete-cascade – Your Common Sense May 19 '17 at 15:56
• Will check that out as well, thanks for sharing! – user3304303 May 19 '17 at 20:29

As we know if want to delete data from referenced table if we delete data from the parent table so for this we use the MySQL cascade feature.

We use MySQL ON DELETE cascade in this case. Just take an example if I have two tables. 1- Parent 2- Child and I want to delete referenced data automatically from the child table if I delete data from the parent table. So for this, we use ON DELETE cascade on child table foreign key. See a complete example using the below link


text:
# Determine phase response from pole-zero plot

I know how to determine the frequency response from the pole-zero diagram given the following formula:

$$\left | H(f) \right | = \frac{\prod \left | (e^{j2\pi f} - a_{i})\right |}{\prod \left | (e^{j2\pi f} - b_{j})\right |}$$

where f is a normalized frequency varying from 0 to $$\frac{1}{2}$$ and a and b are values of zeros and poles respectively.

It is easy with this to draw up the frequency response but how can you determine the phase response (linear, minimal, etc.) with a given equation (and therefore pole-zero diagram) ?


text:
# How do you find the monotonicity, extrema, concavity, and inflection points of f(x)=lnx/sqrt(x)?

Feb 17, 2017

graph{lnx/sqrtx [-0,5, 1000, -2.88, 2]}

#### Explanation:

We start by observing that the function:

$f \left(x\right) = \ln \frac{x}{\sqrt{x}}$

is defined in the interval: $x \in \left(0 , + \infty\right)$, that it is negative for $x < 1$, positive for $x > 1$ and has a single zero for $x = 1$

We can analyze the behavior at the limits of the domain:

${\lim}_{x \to {0}^{+}} \ln \frac{x}{\sqrt{x}} = - \infty$

${\lim}_{x \to \infty} \ln \frac{x}{\sqrt{x}} = 0$

so the function has the line$x = 0$ for vertical asymptote and the line $y = 0$ has horizontal asymptote.

Let's calculate the first and second derivative of the function:

$f ' \left(x\right) = \frac{\frac{\sqrt{x}}{x} - \ln \frac{x}{2 \sqrt{x}}}{x} = \frac{\sqrt{x}}{x} ^ 2 - \ln \frac{x}{2 x \sqrt{x}} = \frac{2 - \ln x}{2 x \sqrt{x}}$

$f ' ' \left(x\right) = \frac{\left(- \frac{2 x \sqrt{x}}{x}\right) - \left(\left(2 - \ln x\right) 3 \sqrt{x}\right)}{4 {x}^{3}} = \frac{- 2 \sqrt{x} - 6 \sqrt{x} + 3 \ln x \sqrt{x}}{4 {x}^{3}} = \frac{3 \ln x - 8}{4 {x}^{2} \sqrt{x}}$

Now we can see that:

(1) $f ' \left(x\right) > 0$ for $2 - \ln x > 0$ that is for $x < {e}^{2}$

so the function is increasing in the interval $\left(0 , {e}^{2}\right)$ and decreasing in $\left({e}^{2} , + \infty\right)$ and has a single critical value in $x = {e}^{2}$ that is a local maximum.

(2) $f ' ' \left(x\right) > 0$ for $3 \ln x - 8 > 0$ or $x > {e}^{\frac{8}{3}}$

so the function is concave down in the interval $\left(0 , {e}^{\frac{8}{3}}\right)$ and concave up in $\left({e}^{\frac{8}{3}} , + \infty\right)$ and has a single inflection point in $x = {e}^{\frac{8}{3}}$.


text:
# Recent questions tagged vector-identities

The directional derivative of $f(x,y,z) = xyz$ at point $(-1,1,3)$ in the direction of vector $\hat{i} – 2 \hat{j} +2 \hat{k}$ is $3\hat{i} – 3 \hat{j} - \hat{k} \\$ $- \dfrac{7}{3} \\$ $\dfrac{7}{3} \\$ $7$
A vector field is defined as ... spherical shell formed by two concentric spheres with origin as the center, and internal and external radii of $1$ and $2$, respectively, is $0$ $2\pi$ $4\pi$ $8\pi$
Given a vector $\overrightarrow{u} = \dfrac{1}{3} \big(-y^3 \hat{i} + x^3 \hat{j} + z^3 \hat{k} \big)$ and $\hat{n}$ as the unit normal vector to the surface of the hemipshere $(x^2+y^2+z^2=1; \: z \geq 0)$ ... $S$ is $- \dfrac{\pi}{2} \\$ $\dfrac{\pi}{3} \\$ $\dfrac{\pi}{2} \\$ $\pi$
For the spherical surface $x^2+y^2+z^2=1$, the unit outward normal vector at th point $\left( \dfrac{1}{\sqrt{2}}, \dfrac{1}{\sqrt{2}}, 0\right)$ is given by $\dfrac{1}{\sqrt{2}} \hat{i} +\dfrac{1}{\sqrt{2}} \hat{j} \\$ $\dfrac{1}{\sqrt{2}} \hat{i} -\dfrac{1}{\sqrt{2}} \hat{j} \\$ $\hat{k} \\$ $\dfrac{1}{\sqrt{3}} \hat{i} +\dfrac{1}{\sqrt{3}} \hat{j} +\dfrac{1}{\sqrt{3}} \hat{k}$
For a position vector $\overrightarrow{r} = x \hat{i}+y \hat{j} + z\hat{k}$ the norm of the vector can be defined as $\mid \overrightarrow{r} \mid = \sqrt{x^2+y^2+z^2}$. Given a function $\phi =\text{ln} \mid \overrightarrow{r} \mid$ ... $\dfrac{\overrightarrow{r}}{\overrightarrow{r} \cdot \overrightarrow{r} } \\$ $\dfrac{\overrightarrow{r}}{\mid \overrightarrow{r} \mid^3}$
The value of the integral over the closed surface $S$ bounding a volume $V$, where $\overrightarrow{r} = x \hat{i} + y \hat{j}+z \hat{k}$ is the position vector and $\overrightarrow{n}$ is the normal to the surface $S$, is $V$ $2V$ $3V$ $4V$
The divergence of the vector $-yi+xj$ is ________.
For the vector $\vec{V}=2yz\hat{i}+3xz \hat{j}+4xy \hat{k}$, the value of $\bigtriangledown$. $(\bigtriangledown \times \vec{V})$ is ________.
A point P $(1, 3,−5)$ is translated by $2\hat{i}+3\hat{j}-4\hat{k}$ and then rotated counter clockwise by $90^\circ$ about the $z$-axis. The new position of the point is $(−6, 3,−9)$ $(−6,−3,−9)$ $(6, 3,−9)$ $(6, 3, 9)$
The value of the line integral $\oint_{c}^{ }\overline{F}.{\overline{r}}'ds$ ,where $C$ is a circle of radius $\dfrac{4}{\sqrt{\pi }}$ units is ________ Here, $\overline{F}(x,y)=y\hat{i}+2x\hat{j}$ and ${\overline{r}}'$ ... $\hat{j}$ are the basis vectors in the $x-y$ Cartesian reference. In evaluating the line integral, the curve has to be traversed in the counter-clockwise direction.
A scalar potential $\varphi$ has the following gradient: $\bigtriangledown \varphi =yz\hat{i}+xz\hat{j}+xy\hat{k}$ . Consider the integral $\int_{c}^{ }\bigtriangledown \varphi .d\overrightarrow{r}$ on the curve $\overrightarrow{r}=x\hat{i}+y\hat{j}+z\hat{k}$. The curve $C$ is ... . The value of the integral is ________
The figure below represents a triangle $PQR$ with initial coordinates of the vertices as $P(1,3)$, $Q(4,5)$ and $R(5,3.5)$. The triangle is rotated in the $X$-$Y$ plane about the vertex $P$ by angle $\theta$ in clockwise direction. If sin$\theta$ = $0.6$ and cos$\theta$ = $0.8$, the new coordinates of the vertex $Q$ are $(4.6, 2.8)$ $(3.2, 4.6)$ $(7.9, 5.5)$ $(5.5, 7.9)$
Let $\phi$ be an arbitrary smooth real valued scalar function and $\overrightarrow{V}$ be an arbitrary smooth vector valued function in a three-dimensional space. Which one of the following is an identity? Curl$(\phi \overrightarrow{V})$ = $\bigtriangledown$($\phi$ ... $\overrightarrow{V}=0$ Div($(\phi \overrightarrow{V})$ ) = $\phi$ Div$\overrightarrow{V}$
Consider a velocity field $\overrightarrow{V}=k(y\hat{i}+x\hat{k})$ , where $K$ is a constant. The vorticity, $Ω_Z$ , is $-K$ $K$ $-K/2$ $K/2$
Divergence of the vector field $x_2z\hat{i}+xy\hat{j}-yz\hat{k}$ at $(1,-1,1)$ is $0$ $3$ $5$ $6$
Curl of vector $\overrightarrow{F}=x^2z^2\hat{i}-2xy^2z\hat{j}+2y^2z^3\hat{k}$ is $(4yz^3+2xy^2)\hat{i}+2x^2z\hat{j}-2y^2z\hat{k}$ $(4yz^3+2xy^2)\hat{i}-2x^2z\hat{j}-2y^2z\hat{k}$ $2xz^2\hat{i}-4xyz\hat{j}+6y^2z^2\hat{k}$ $2xz^2\hat{i}+4xyz\hat{j}+6y^2z^2\hat{k}$
Which one of the following describes the relationship among the three vectors, $\hat{i}+\hat{j}+\hat{k}$ , $2\hat{i}+3\hat{j}+\hat{k}$ and $5\hat{i}+6\hat{j}+4\hat{k}$ ? The vectors are mutually perpendicular The vectors are linearly dependent The vectors are linearly independent The vectors are unit vectors


text:
# Which Numbers Would Crash this Function?

Which values of x and y will cause a crash with some C compilers?

int f(int x, int y) {
return (y==0) ? 0 : (x/y);
}

• Since C's ternary operator shortcuts, I would say none would. This question doesn't seem to fit the format for this site, which is focused on program puzzles and code golf. See the faq for details codegolf.stackexchange.com/faq. – Steven Rumbalski Jan 12 '12 at 14:48
• This isn't code golf, but is a puzzle. There is an answer, and it's just a couple of numbers. – ugoren Jan 12 '12 at 14:51
• I stand corrected. – Steven Rumbalski Jan 12 '12 at 14:59
• Actually, judging by the K&R book, this function really must never crash. But by the ANSI C standard, the behavior in the particular crashing case is undefined, and with x86 compilers it crashes. – ugoren Jan 12 '12 at 15:05
• @dmckee, If you give the right answer, you're the winner. What cretirion could be more clear and objective? There's only one answer (or do you have another example?) – ugoren Jan 12 '12 at 18:10

-2147483648 (INT_MIN) and -1

#include <stdio.h>
#include <limits.h>
int f(int x, int y) {
return (y==0) ? 0 : (x/y);
}
int main() {
int r = f(INT_MIN, -1);
printf("%d\n", r);
return 0;
}

\$ gcc -Wall division.c && ./a.out # => zsh: floating point exception ./a.out

• Indeed. Though this should give a warning, because 2147483648 isn't a valid integer. – ugoren Jan 12 '12 at 14:57
• Yes, that's why I used INT_MIN after, to use a valid int. I guess the reason is 2147483648 is not a valid int, since INT_MAX is 2^31-1 with 32-bit int. – eregon Jan 12 '12 at 14:59
• Ah. Two's complement. I missed that. – Steven Rumbalski Jan 12 '12 at 15:00
• Yes, it should compile cleanly with INT_MIN (which is -2147483648). – ugoren Jan 12 '12 at 15:02

The right answer is already given, but I immediately thought about Microsoft Pex.

Pex automatically generates test suites with high code coverage. Right from the Visual Studio code editor, Pex finds interesting input-output values of your methods, which you can save as a small test suite with high code coverage. Microsoft Pex is a Visual Studio add-in for testing .NET Framework applications

After adding your puzzle in the sandbox site, it finds the answer in a few seconds, the same as eregons answer. (click ask pex)

Note: it does it in C#, but the language is not really relevant.

• x: int.MinValue
• y: -1
• Exception: OverflowException
• Message: Arithmetic operation resulted in an overflow.
• Nice. It surely doesn't brute-force it, because it wouldn't end in a few seconds. I guess someone in MS realized that numbers around 0 and MAX_INT are always interesting. – ugoren Jan 17 '12 at 15:19
• Hopefully it's a little more clever than that. It might look at (x/y) and know that INT_MIN, -1, 0 etc. are all problem cases for that expression, and try to reverse engineer a way to produce those values at the time of evaluation. – Clueless Jan 18 '12 at 21:01


text:
Solve the following differential equation and find the particular solution.

4y''+24y'+37y=0, y'(pi)=0 and y(pi)=1

• You can write down the general solution by inspection (i.e., what function would have y'' = -4y), but we'll derive it.

This is a second-order, linear, ordinary, homogeneous differential equation with constant coefficients. Look for a solution of the form y = exp(k*x). This results in the characteristic equation:

k^2 + 4 = 0

k = +2i, -2i, where i = sqrt(-1)

The roots are imaginary, so by ysing Euler's relationship, we can write the solution as:

y(x) = a*sin(2x) + b*cos(2x)

where a and b are the constants of integration.

Differentiating, we get:

y'(x) = 2a*cos(2x) - 2b*sin(2x)

Now plug in the initial conditions and solve for a and b to get the particular solutions for each of the cases given.

y(0) = 0, y'(0) = 1 implies that:

0 = a*sin(0) + b*cos(0)
b = 0
and

1 = 2a*cos(0) - 2b*sin(0)
a = 1/2

The particular solution would be:

y(x) = (1/2)*sin(2x)

----
y(0) = 1, y'(0) = 0 implies that:

1 = a*sin(0) + b*cos(0), so b = 1
and
0 = 2acos(0) - 2b*sin(0)
so a = 0

and
y(x) = b*cos(2x)

----------
y(0) = 0, y(1) = 1 implies that:

b = 0, and

1 = a*sin(2)

a = 1/sin(2)

y(x) = (sin(2x))/sin(2)


text:
#### The promises and pitfalls of Stochastic Gradient Langevin Dynamics

##### Nicolas Brosse, Alain Durmus, Eric Moulines

Stochastic Gradient Langevin Dynamics (SGLD) has emerged as a key MCMC algorithm for Bayesian learning from large scale datasets. While SGLD with decreasing step sizes converges weakly to the posterior distribution, the algorithm is often used with a constant step size in practice and has demonstrated successes in machine learning tasks. The current practice is to set the step size inversely proportional to $N$ where $N$ is the number of training samples. As $N$ becomes large, we show that the SGLD algorithm has an invariant probability measure which significantly departs from the target posterior and behaves like Stochastic Gradient Descent (SGD). This difference is inherently due to the high variance of the stochastic gradients. Several strategies have been suggested to reduce this effect; among them, SGLD Fixed Point (SGLDFP) uses carefully designed control variates to reduce the variance of the stochastic gradients. We show that SGLDFP gives approximate samples from the posterior distribution, with an accuracy comparable to the Langevin Monte Carlo (LMC) algorithm for a computational cost sublinear in the number of data points. We provide a detailed analysis of the Wasserstein distances between LMC, SGLD, SGLDFP and SGD and explicit expressions of the means and covariance matrices of their invariant distributions. Our findings are supported by limited numerical experiments.

arrow_drop_up


text:
# NeuralLayer

Namespace: Models

A layer of neurons (perceptrons).

## Nested types and modules

 Type Description HyperPars Neural layer hyper-parameters. Pars<'T> Neural layer parameters.

### Functions and values

 Function or value Description  defaultHyperPars  Signature: HyperPars  pars mb hp  Signature: mb:ModelBuilder<'?176100> -> hp:HyperPars -> Pars<'?176101> Type parameters: '?176100, '?176101 Creates the parameters for the neural-layer in the supplied model builder mb using the hyper-parameters hp. The weights are initialized using random numbers from a uniform distribution with support [-r, r] where r = 4 * sqrt (6 / (hp.NInput + hp.NOutput)). The biases are initialized to zero.  pred pars input  Signature: pars:Pars<'?176103> -> input:ExprT -> ExprT Type parameters: '?176103 Returns an expression for the output (predictions) of the neural layer with parameters pars given the input input. If the soft-max transfer function is used, the normalization is performed over axis 0.  regularizationTerm pars  Signature: pars:Pars<'?176105> -> ExprT Type parameters: '?176105 Calculates sum of all regularization terms of this layer.


text:
# If the Perimeter of a Sector of a Circle of Radius 6.5 Cm is 29 Cm, Then Its Area is - Mathematics

MCQ

If the perimeter of a sector of a circle of radius 6.5 cm is 29 cm, then its area is

•  58 cm2

• 52 cm2

•  25 cm2

• 56 cm2

#### Solution

We know that perimeter of a sector of radius l=2r+θ/360xx2pir ...............(1)

We have given perimeter of the sector and radius of the sector and we are asked to find the area of the sector. For that we have to find the sector angle.

Therefore, substituting the corresponding values of perimeter and radius in equation

(1) we get,

29=2xx6.5+θ/360xx2pixx6.5.............(2)

We will simplify equation (2) as shown below,

29=2xx6.5(1+θ/360xxpi)

Dividing both sides of the equation by 2xx6.5, we get,

29/2xx6.5=(1+θ/360xxpi)

Subtracting 1 from both sides of the equation we get,

29/2xx6.5-1=θ/360xxpi.............(3)

We know that area of the sector = θ/360xxpi^2

From equation (3), we get

Area of the sector  = (29/(2xx6.5)-1)r^2

Substituting r=6.5 we get,

Area of the sector =(29/(2xx6.5)-1)6.5^2

Area of the sector=((29xx6.5^2)/(2xx6.5)-6.5^2)

Area of the sector=((29xx6.5)/2-6.5^2)

Area of the sector=(188.5/2-42.25)

Area of the sector=(94.25-42.25)

Area of the sector=52

Therefore, area of the sector is 52 cm^2

Is there an error in this question or solution?

#### APPEARS IN

RD Sharma Class 10 Maths
Chapter 13 Areas Related to Circles
Q 22 | Page 70


text:
• ### A first endeavor into generative art

April 17, 2020

Last year we organized an internal conference at my workplace and I volunteered to put together a booklet with the abstracts of the presentations. I wanted to add photos of the authors, but I did not want them to look all the same.Actually, graphic design and layout editing was not new to me, I’ve always had a thing for this field. At some point during my bachelor’s in Economics I even considered moving abroad and studying it instead of finishing that degree. Instead of doing so, I just volunteered to design the faculty magazine. I came up with the idea to have the photos on top of two rectangles of the same size but of two different colors, a bit offset from the photo – every photo should be paired with differently offset rectangles to add some unique design. Of course, I did not want to do this by hand, but that’s what I know Python for.

• ### Introducing gpxslicer

January 28, 2020

I have recently released my first Python package, gpxslicer, a simple tool to cut GPX track logs into smaller segments. It is now available on GitHub and PyPI. The motivation behind creating it was simple: I wanted to automate tasks that I had done by hand too many times.

• ### Understanding Overpass, the API of OpenStreetMap

January 17, 2020

If you want to use spatial data from OpenStreetMap, OpenStreetMap is more than just a free map: it is also a free database of global geographical data. If you are not familiar with it, check out its Wiki to learn more. one way to get it is via Overpass, Read more about the Overpass API and its various endpoints here. a read-only API of the OpenStreetMap database. While the API is extremely flexible, its unique language, Overpass QL is not very intuitive. This article takes a very simple query and dissects it into its smallest pieces. This will help you understand (and write) such queries.

• ### Alphabetical sorting is hard

November 24, 2019

It really was a great idea. As usual, I took a problem that I randomly ran into and wanted to find a solution to. I was not sure if I could implement the solution, but I knew I could describe it. It happened when I was working on a project where I got some data about municipalities in Hungary. I thought it would be handy to sort them alphabetically so that the user of the final product can easily find the place they are interested in. However, due to the unusual letters in the Hungarian alphabet, such as ő or gy, collation is not trivial. But I knew I could find a way to solve this!

• ### The autumn of 1929 – the story of two hikes

October 29, 2019

I was going through the documents of my great-grandfather, Lajos Frenyó when I found a couple of folded papers in one of the notebooks. I had already known that he really liked hiking but I did not have any material proof of this hobby apart from the photo used as the cover image of this post. That is, up until that moment, because these papers contained a very detailed account documenting two trips in the Tatra mountains. This post contains these two reports with my comments.

• ### EXPECT A HAPPY HOBBY

December 2, 2018

Do you know what a COYOTE TOOTHACHE and a CHECKBOOK PHOTOCOPY have in common? If written in uppercase, all the letters of these expressions appear in the Cyrillic alphabet. That is, if we take a more relaxed definition of letters being the same shape: in many typefaces, K and К and Y and У do not look the same, just very similar. Although, to be precise, if somebody would try to read these using the Cyrillic alphabet, they would read “souote tootnase” and “sneckvook rnotosoru”, respectively.

I started thinking about this when I realized that I had never seen a Russian license plate with letters that do not also appear in the Latin alphabet. So I started to wonder about two things: is this observation true in general? If so, what words could we make up that would consist only of such letters?

• ### Nicely formatted transit schedules

August 18, 2018

I enjoy hiking, which most of the times involves using public transportation to get to the start of my hike and to get back home. Planning these trips used to be a major chore in Hungary before 2016, as there was no unified schedule database: one could only plan trips by train or bus, not together. During these times I came up with a timetable format in which I manually collected transit options using the bus and train planner websites as well as a map to came up with potential routes. These days transit information is available via the Google Directions API, so I decided to revisit this format and I developed a script that creates it automatically.

• ### Sunrise, sunset

March 8, 2018

I grew up in Budapest and moved to the Netherlands a few years ago. I could not ignore the fact that the Sun has very different patterns: it rises later and sets later here than in Budapest. However, this difference is not uniform: my feeling was that the sun rises much later and sets about the same time during the winter. I saw the inverse in the summer: Dutch summer evenings are much longer, but dawn does not lag behind that much. I wanted to verify this feeling in a scalable manner, so I created a website (code here) where you can pick two arbitrary locations on the globe and see a graph with their dawn/dusk times through the year.

• ### Where have the camels gone?

November 30, 2016

teveclub.hu used to be one of the most well-known websites among Hungarian teenagers. It is a Neopets clone where you can raise your own camel: feed it, and teach it various tricks day by day. I had the feeling that the site was slowly dying. I used data from archive.org to verify this hypothesis and I found that it was true: the total number of camels in the system has dropped from the ~320 thousand peak in 2006 to less than 26 thousand in 2018.

• ### Grab a drink while you wait for the bus

August 20, 2015

I always found it fascinating that there are several bus stops in Hungary which are called “{municipality name}, Cooperative Liquor Store” (szövetkezeti italbolt in Hungarian). It might get somewhat lost in translation that such a name very much reminds the reader of the socialist era it was given to the bus stop.

• ### Hungarian municiaplity name prefixes

August 6, 2015

Hungarian municipalities have unique names that consist of one (potentially compound) word. This was not the case until the end of the 19th century: multiple villages could have the same name, sometimes even in the same county. This caused trouble not only for the postal service but also related to taxation and conscription. Hence the standardization: every name must be unique; in case of a duplcate, the municipality names got a prefix based on their general location. I investigated these prefixes: their spatial distribution and the origin of those names.

• ### Bad idea of the day: toll on M0, the ring road around Budapest

December 11, 2014

An article published yesterday in Népszabadság reveals that the Hungarian budget for 2015 includes a proposal to introduce tolls on several motorway segments that are toll-free today. To me, this sounds like a bad idea.

• ### How far up does the tram go?

November 25, 2013

Historically, there were three relatively hilly tram lines in Budapest: 58, 59, and 61. Service on line 58 has been suspended since 1977. In this case, “suspension” includes the tracks having been removed and paved over. Based on this, I do not think service will restart anytime soon. But how far up do these actually go? And which one is the steepest?

• ### Revolutionary street names

March 15, 2013

Every Hungarian knows that almost every village in the country will have a street named after Lajos Kossuth, revolutionary and politician, and another named after Sándor Petőfi, an emblematic hero-poet – both of whom took part in the Hungarian Revolution of 1848. But where exactly are these streets?


text:
# Butterworth cutoff frequency normalization

The issue: I am trying to reproduce the step detection technique as described in this paper. You can see the proposed step detection in the image below. The first part of this technique is to use a 2nd order Butterworth digital high-pass filter with a sampling rate fs=50 Hz and cut off frequency fc=1000 Hz. Is this a valid cut off frequency (fc>>fs)?

The problem: I know that i have to normalize the cut-off frequency by fs/2. For example in python according to scipy.butter documentation i have:

fs = 50
fc = 1000  # Cut-off frequency of the filter
w = fc / (fs / 2) # Normalize the frequency
b, a = signal.butter(2, w, 'hp')

But this is not correct because w must be 0 to 1 where 1 is the Nyquist frequency.

• Probably a typo. They later filter the signal with a 5 Hz lowpass, so a high pass filter with $f_c=1000Hz$ makes no sense whatsoever. – Hilmar Jul 2 at 15:39


text:
# Differential equation: Spring/Mass system of driven motion with damping

1. ### TeenieBopper

29
1. The problem statement, all variables and given/known data
A 32 pound weight stretches a spring 2 feet. The mass is then released from an initial position of 1 foot below the equilibrium position. The surrounding medium offers a damping force of 8 times the instantaneous velocity. Find the equation of motion if the mass is driven by an external force of 2cos(5t).

2. Relevant equations
F=kx
m=W/g

m$\frac{d^{2}x}{dt^{2}}$+$\beta$$\frac{dx}{dt}$+kx=f(t)

3. The attempt at a solution

I found that k=16$\frac{lb}{ft}$ and m=1 slug. This gets me the following equation:

$\frac{d^{2}x}{dt^{2}}$+$\beta$$\frac{dx}{dt}$+16x=2cos(5t)

I'm at a loss for how to determine $\beta$, which is the damping force of 8 times the instantaneous velocity. I don't know how to determine instantaneous velocity. I know that once I have $\beta$, I can just use a LaPlace transform to find x(t). But $\beta$ is my stumbling block right now.

As I was writing this, it occured to me that $\frac{dx}{dt}$=instantaneous velocity and that would make $\beta$=8. That in turn makes the problem very easy to solve. Am I correct in this thinking?

We kind of rushed through this application in class the other day. Thanks in advance for any help you're able to provide.

2. ### rock.freak667

6,219
Yeah I would agree that β=8 here. Just make sure your initial conditions are correct with the proper signs.

Know someone interested in this topic? Share a link to this question via email, Google+, Twitter, or Facebook