text:
# Dynamic array implementation using C++

I implemented a basic dynamic array using C++.

When deleting an element and shifting the others, the last element will be twice repeated (the original still exists after copying). I want to avoid memory leaking by deallocating the last element of the array. Currently, I do this by shrinking once after a number of deletions. Are there better solutions?

Finally, I am interested in some feedback on this implementation.

#include <iostream>
#include <stdexcept>

using namespace std;

class DynamicArray {
protected:
int size;
int* arr;
int length;

void grow() {
copyToNewSize(size * 2);
}

void shrink() {
copyToNewSize(size / 2);
}

void copyToNewSize(int newSize) {
int* temp = new int[newSize];
if (newSize > size)
for (int i = 0; i < size; i++) {
temp[i] = arr[i];
}
else
for (int i = 0; i < newSize; i++) {
temp[i] = arr[i];
}
delete[] arr;
size = newSize;
arr = temp;
}

void checkIndex(int index) {
if (index >= length || index < 0)
throw "Index is out of the array range!";
}

public:
DynamicArray(int startingSize) {
size = startingSize;
arr = new int[size];
length = 0;
}

~DynamicArray() {
delete[] arr;
}

int push(int value) {
length++;
if (length == (size + 1))
grow();
arr[length - 1] = value;
return length;
}

int pop() {
length--;
int value = arr[length];
// memory leaking , delete arr[length]
if (length <= size / 2)
shrink();
return value;
}

int insert(int index, int value) {
checkIndex(index);
length++;
if (length == (size + 1))
grow();
for (int i = length - 1; i > index; i--) {
arr[i] = arr[i - 1];
}
arr[index] = value;
return length;
}

int remove(int index) {
checkIndex(index);
int value = arr[index];
length--;
for (int i = index; i < length; i++)
arr[i] = arr[i + 1];
// memory leaking , delete arr[length]
if (length <= (size / 2))
shrink();
return value;
}

int get(int index) {
checkIndex(index);
return arr[index];
}

void set(int index, int value) {
checkIndex(index);
arr[index] = value;
}

int search(int value) {
for (int i = 0; i < length; i++) {
if (arr[i] == value)
return i;
}
return -1;
}

int getLength() {
return length;
}
}

• Do you have any specific reason for not using std::vector<int> or one of the other standard containers?
– jdt
Sep 20 at 11:54
• @JohanduToit Yes, learning to code. Sep 20 at 12:38

First of all, there is a major problem with your class: it does not respect the rule of three/five/zero:

• it has a non trivial destructor that destroys memory allocated in constructor

• it neither defines nor deletes the copy constructor and assignment operator Let us look at the following code:

  DynamicArray dynarr[16];
// initialize values in dynarr
if (...) {
// opens a nested block
DynamicArray dynarr2 = dynarr;    // copy construct the new DynamicArray (1)
// use it
}
// dynarr2 goes out of scope (2)

At (1), the compiler generated copy constructor will blindly copy the member, having dynarr and dynarr2 share their inner int array.

At (2), the dtor for dynarr2 will delete the shared inner array: ZAP!... dynarr now has a dangling pointer, Undefined Behaviour is ensured from there....

There is another possible error in size management. You consistently divide it by 2 when removing elements and multiply it by 2 when adding. Fine. Except that if you let the size reach 0 by removing the last element of a DynamicArray 0*2 is still 0 so the size will be definitively stuck at 0! You must handle that corner case by preventing the size to reach 0 in shrink.

What follow are only minor possible improvements.

• Your code uses using namespace std;

This is not an error because it is allowed by the language, and is even common in many tutorials. It is a nice trick that allows to use all the goodies from the standard library without the std:: prefix. But, it does import a number of useless symbols into the current namespace, somehow defeating the whole namespace concepts. In production code, best practices recommend to never use using namespace std but only import the relevant symbols. Only a cosmetic improvement.

• in checkIndex, you use throw "Index is out of the array range!";

This actually throws a pointer to a string litteral. Here again it is not an error since it is allowed by the language. But best practices recomment to only throw objects of (subclasses of) the std::exception class. Users of your class will probably not expect to have to catch a char pointer. You'd better use an out_of_range or a runtime_error exception if you think it is not worth declaring a custom exception

• You compare size and newsize in copyToNewSize to know how many elements should be copied. But in fact you have only to copy length elements... This one is only a tiny optimization.

For your initial question, there is nothing bad in only shrinking after a number of removals, because a shrink involve reallocation and a copy of the elements, so it is an expensive operation. For that reason, you should even considere stop shrinking below a threshold (for example 8 elements). As a bonus, it will directly prevent size to reach 0, and you could even make that minimal size an optional parameter of your constructor.

• and you could even make that minimal size an optional parameter of your constructor. - Then you'd have to store it somewhere. That sounds unlikely to be good, although if you're implementing this for real (rather than a learning exercise) then making it different from std::vector is a good idea, otherwise you'd just use std::vector. I'd be more inclined to make a tuning option like that an optional template parameter, or possibly a static member variable. Sep 21 at 3:15
• @PeterCordes: I generally avoid integer templates, because they are a nightmare in a library: either you put the full definition in headers, or you have to instantiate a number of concrete classes and users will be restricted to them. I have never found a correct implementation of multidimensional arrays in C++ because of that (inner dimensions can only be constexpr). Sep 21 at 7:29
1. Consider using size_t instead of int. The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to problems, particularly as 64-bit architectures become more prevalent.

2. It is generally bad practice to repeat code that does the same thing. Consider changing copyToNewSize to something like this:

void copyToNewSize(size_t newSize) {
int* temp = new int[newSize];
size_t copySize = std::min(size, newSize);
for (size_t i = 0; i < copySize; i++) {
temp[i] = arr[i];
}
delete[] arr;
size = newSize;
arr = temp;
}

1. I would suggest that you rename size to allocatedSize to avoid confusion between size and length.
• 64-bit architectures are already widespread; what's still left to change is that real-world memory capacities continue to grow, so it's becoming more realistic (and maybe less rare in real-world usage) to actually have arrays that large. Sep 21 at 3:17
• Also, std::copy exists, can be a good idea to use it instead of open-coding a copy loop. Sep 21 at 3:19
• #pragma omp parallel for on a copy loop? Yeah, could be for very large copies (like maybe more than 4GiB), on systems like a big Xeon where a single core can't saturate memory-controller bandwidth. (Why is Skylake so much better than Broadwell-E for single-threaded memory throughput?). If you have so many large copies to do that it's worth considering threads just for that, though, probably algorithmic optimizations to avoid copying so much will be even better. Or see my comments on mdfst13's answer re: Linux mremap to avoid physical copying. Sep 21 at 12:02
• (Or if other cores can be doing something useful while some are just copying, that might be good for overall throughput, unless multiple other threads are waiting for this copy to complete. On some CPUs there are diminishing returns for using even more threads to max out copy bandwidth, although on current Skylake-Xeon it's fairly linear for quite a few cores because the per-core memory bandwidth is so small (compared to a desktop and also as a fraction of the available aggregate memory-controller bandwidth)) Sep 21 at 12:05
• You forgot to add any compiler flags on TIO, so that was gcc -O0. If you just meant to link the code but not try to run it on the server, godbolt.org/z/jW91snGdj lets you look at the asm. (using gcc -O3 -fopenmp. Without -fopenmp, #pragma omp does nothing.) Sep 21 at 16:20

### Don't talk like a pirate

I would prefer the name array (another reason not to using namespace std;) to arr. And I'd prefer a more descriptive name like data or numbers to either.

### Don't waste work

    int push(int value) {
length++;
if (length == (size + 1))
grow();
data[length - 1] = value;
return length;
}

You add and subtract three times. Consider

    int push(int value) {
if (length == size) {
grow();
}

data[length] = value;
length++;
return length;
}

In general, I would avoid the statement form of control structures. That can lead to odd, hard to find bugs. Worse, you use it inconsistently, which makes the code harder to read.

### Fragile code

        if (length <= size / 2)
shrink();

and

    void shrink() {
copyToNewSize(size / 2);
}

Combined these are fragile. To work properly, you need size / 2 to be the same in both places. Consider

        size_t bound = size / 2;
if (length <= bound) {
copyToNewSize(bound);
}

Now it has to be the same in both places. Another alternative

    void shrinkIfNecessary() {
size_t bound = size / 2;
if (length <= bound) {
copyToNewSize(bound);
}
}

Then replace the if and call to shrink with shrinkIfNecessary.

In general, you should try to avoid parallel logic. If you need the same logic in two places, try to abstract it out into at least a variable (e.g. bound here) or a function (e.g. shrinkIfNecessary).

It's natural to think that grow should have a shrink. But here, the shrinking operation is triggered differently. They aren't mirror images of each other. You have to grow any time you exceed the bounds. You don't need to shrink every time. So it actually makes sense to have grow and shrinkIfNecessary instead.

You also might consider moving the 2 to a constant, e.g. GROWTH_FACTOR. But that will work fine even if inconsistent between growing and shrinking, so it's less important.

### std::copy

        if (newSize > size)
for (int i = 0; i < size; i++) {
temp[i] = arr[i];
}
else
for (int i = 0; i < newSize; i++) {
temp[i] = arr[i];
}

In this, you copy manually. But you don't need to do that. C++ has std::copy. So you could just say

        std::copy(arr, arr + std::min(size, newSize), temp);

The std::min was already posted here.

Note that std::copy requires #include <algorithm>.

This would get around the entire question of int vs. size_t vs. auto as regards to the loop index variables. No more loops means no more loop indexes.

### The C++ way

C++ also has std::vector, which would get around the entire class.

### The C way

If you prefer to reinvent the wheel, you might consider if you want to go all the way and return to the C memory management. Why C? Because in C, you have realloc, which can make arrays smaller or larger. Usually when making an array smaller, it would use the same memory and free just what is at the end. C++ doesn't have that capability (except in that C++ has access to the C routines). Of course, if you do that, you want to stop using new and delete in favor of calloc/malloc and free.

The realloc function also handles the copying for you if necessary. But it won't always be necessary, because realloc will usually reuse the existing array when making it smaller. And it will sometimes use the existing array when making it bigger as well.

### Duplicates

When deleting an element and shifting the others, the last element will be twice repeated (the original still exists after copying).

In one sense, this is harmless. If you track the size correctly and initialize the memory before using, this might be true, but you'd never know.

If you are concerned about leaving traces in your program, note that realloc can make an array smaller efficiently enough that you could call it on every pop or remove. However, you'd still likely prefer to grow less frequently. Because at least some of the time, it would cause the array to need to be copied.

You might also consider manually clearing the entry. E.g. in remove:

        data[length] = 0;

That's the kind of thing you'd do if the data were sensitive for some reason.

• std::vector unfortunately can't use realloc because it has to work on non-trivially-copyable types (i.e. whose object-representation may need to change when copied to a new address, or just whose copy-constructor has a side-effect such as debug logging.). But even more unfortunately, not even in a template specialization for trivially-copyable types is easy: C++ has replaceable new, and there's a guarantee that if std::vector allocates, it's via calls to new, so user-defined new will run. This replacement might be in a different compilation unit so you can't template on it. Sep 21 at 10:16
• IDK why C++ has refused to add a try_realloc allocator interface that could avoid copying, but it makes std::vector pretty garbage for huge arrays, especially compared to what it could be doing on Linux where the mremap(2) system call does this at page granularity, trying to extend an existing mapping. And with MREMAP_MAYMOVE can always avoid copying by remapping the existing physical pages to the start of a larger extend of virtual address space if there were wasn't room to grow at the original spot. (Still TLB misses though.) Sep 21 at 10:22
• So basically C++ requires std::vector to suck at clever reallocation optimizations, although if an implementation could detect that new wasn't replaced (or promise via a command line arg), the as-if rule would let std::vector use smarter realloc. Howard Hinnant said on SO) that his attempts to improve things for C++11 didn't get traction. IMO adding a try_realloc interface to the language would have been easy; implementations could always define it as new + copy + delete or return false. Sep 21 at 10:29
• So yeah, writing your own container that used realloc or even mmap / mremap (intended for large allocations where bypassing a free-list makes sense) could be a case where it's actually interesting for real use, not just as a learning exercise. Sep 21 at 10:31
• @PeterCordes std::vector is a template (and so is std::allocator), templates can have specialisations. std::vector<TriviablyCopyable> can use realloc Sep 21 at 12:39


text:
# Half-integer

In mathematics, a half-integer is a number of the form

${\displaystyle n+{1 \over 2}}$,

where ${\displaystyle n}$ is an integer. For example,

4½, 7/2, −13/2, 8.5

are all half-integers.

Half-integers occur frequently enough in mathematical contexts that a special term for them is convenient. Note that a half of an integer is not always a half-integer: half of an even integer is an integer but not a half-integer. The half-integers are precisely those numbers that are half of an odd integer, and for this reason are also called the half-odd-integers. Half-integers are a special case of the dyadic rationals, numbers that can be formed by dividing an integer by a power of two.[1]

## Notation and algebraic structure

The set of all half-integers is often denoted

${\displaystyle \mathbb {Z} +{1 \over 2}.}$

The integers and half-integers together form a group under the addition operation, which may be denoted[2]

${\displaystyle {\frac {1}{2}}\mathbb {Z} }$.

However, these numbers do not form a ring because the product of two half-integers cannot be itself a half-integer.[3]

## Uses

### Sphere packing

The densest lattice packing of unit spheres in four dimensions, called the D4 lattice, places a sphere at every point whose coordinates are either all integers or all half-integers. This packing is closely related to the Hurwitz integers, which are quaternions whose real coefficients are either all integers or all half-integers.[4]

### Physics

In physics, the Pauli exclusion principle results from definition of fermions as particles which have spins that are half-integers.[5]

The energy levels of the quantum harmonic oscillator occur at half-integers and thus its lowest energy is not zero.[6]

### Sphere volume

Although the factorial function is defined only for integer arguments, it can be extended to fractional arguments using the gamma function. The gamma function for half-integers is an important part of the formula for the volume of an n-dimensional ball of radius R,[7]

${\displaystyle V_{n}(R)={\frac {\pi ^{n/2}}{\Gamma ({\frac {n}{2}}+1)}}R^{n}.}$

The values of the gamma function on half-integers are integer multiples of the square root of pi:

${\displaystyle \Gamma \left({\frac {1}{2}}+n\right)={\frac {(2n-1)!!}{2^{n}}}\,{\sqrt {\pi }}={(2n)! \over 4^{n}n!}{\sqrt {\pi }}}$

where n!! denotes the double factorial.

## References

1. ^ Sabin, Malcolm (2010), Analysis and Design of Univariate Subdivision Schemes, Geometry and Computing, 6, Springer, p. 51, ISBN 9783642136481.
2. ^ Turaev, Vladimir G. (2010), Quantum Invariants of Knots and 3-Manifolds, De Gruyter Studies in Mathematics, 18 (2nd ed.), Walter de Gruyter, p. 390, ISBN 9783110221848.
3. ^ Boolos, George; Burgess, John P.; Jeffrey, Richard C. (2002), Computability and Logic, Cambridge University Press, p. 105, ISBN 9780521007580.
4. ^ John, Baez (2005), "On Quaternions and Octonions: Their Geometry, Arithmetic, and Symmetry by John H. Conway and Derek A. Smith", Bulletin of the American Mathematical Society, 42: 229–243, doi:10.1090/S0273-0979-05-01043-8.
5. ^ Mészáros, Péter (2010), The High Energy Universe: Ultra-High Energy Events in Astrophysics and Cosmology, Cambridge University Press, p. 13, ISBN 9781139490726.
6. ^ Fox, Mark (2006), Quantum Optics : An Introduction, Oxford Master Series in Physics, 6, Oxford University Press, p. 131, ISBN 9780191524257.
7. ^ Equation 5.19.4, NIST Digital Library of Mathematical Functions. http://dlmf.nist.gov/, Release 1.0.6 of 2013-05-06.

format: plain


text:
direct sum of representation of product groups

Given two finite groups $$G_1$$ and $$G_2$$, and some representations $$\rho_1: G_1 \to V_1$$ and $$\rho_2: G_2 \to V_2$$, it seems the standard way to create a representation for $$G_1 \times G_2$$ is to use the tensor product $$\rho_1(g_1) \otimes \rho_2(g_2) \quad g_1,g_2 \in G_1,G_2.$$ It seems to me that one could also use the direct sum $$\rho_1(g_1) \oplus \rho_2(g_2)$$, because the blocks in the matrix form of the representation do not interact and one gets the desired effect. Given that this representation could have a lower dimension than using tensor product, why is it not used?

When $$V_1$$ and $$V_2$$ are representations of $$G_1$$ and $$G_2$$ respectively, I'll use $$V_1 \boxtimes V_2$$ to mean the representation of $$G_1 \times G_2$$ with underlying vector space $$V_1 \otimes_{\mathbb{C}} V_2$$, and $$V_1 \boxplus V_2$$ to mean the representation of $$G_1 \times G_2$$ with underlying vector space $$V_1 \oplus V_2$$.
If $$V$$ is an irreducible representation of $$G_1 \times G_2$$, then $$V$$ is isomorphic to $$V_1 \boxtimes V_2$$ for some irreducible representations $$V_1$$ and $$V_2$$ of $$G_1$$ and $$G_2$$ respectively. This means that if we know the representations of $$G_1$$ and $$G_2$$, then using the $$\boxtimes$$ construction we can get to all the (irreducible) representations of $$G_1 \times G_2$$. Conversely, the $$\boxtimes$$ product of two irreducible representations always produces an irreducible representation of $$G_1 \times G_2$$.
On the other hand, $$V_1 \boxplus V_2$$ is always reducible as a $$G_1 \times G_2$$ representation, since both vector subspaces $$V_1$$ and $$V_2$$ are stable under the $$G_1 \times G_2$$ action. On the $$V_1$$ subspace, really only the $$G_1$$ part of the group acts, and the $$G_2$$ part acts trivially, and similarly for the $$V_2$$ subspace. We cannot produce all irreducible representations of $$G_1 \times G_2$$ using this construction, which can already be seen in the example $$G_1 = G_2 = \mathbb{Z} / 2 \mathbb{Z}$$.


text:
Home / Arithmetic Aptitude / Partnership :: Discussion

Discussion :: Partnership

1.  How much did Rohit get as profit at the year-end in the business done by Nitin, Rohit and Kunal? I. Kunal invested Rs. 8000 for nine months, his profit was $$\frac { 3 } { 2 }$$ times that of Rohit's and his investment was four times that of Nitin. II. Nitin and Rohit invested for one year in the proportion 1 : 2 respectively. III. The three together got Rs. 1000 as profit at the year end.
2.  A. Only I and II B. Only I and III C. Question cannot be answered even with the information in all the three statements. D. All I, II and III E. None of these

Explanation :

and II give:

K = Rs. (8000 x 9) for 1 month = Rs. 72000 for 1 month.

N = Rs.[$$\frac { 1 } {4 }$$x8000x12]for 1 month = Rs. 24000 for 1 month.

R = Rs. 48000 for 1 month.

K : N : R = 72000 : 24000 : 48000 = 3 : 1 : 2.

III gives, total profit = Rs. 1000.

Rohit's share = Rs[1000x$$\frac { 2 } { 6 }$$]= Rs. 333$$\frac { 1 } { 3 }$$

Be The First To Comment


text:
# Analytic ZCB call option under Vasicek

The call option with strike $X$ and maturity $T$ on a ZCB maturing at time $S$, where $T\le S$, is $$ZBO(t,T,S,X)=E_t[e^{-\int_t^Tr_sds}(P(T,S)-X)^+]$$ The ZCB price is denoted by $$P(t,T)=E_t[e^{-\int_t^Tr_sds}]$$ I am familiar with the Black-Scholes metholodogy of deriving the call option price from first principles, and I am interested in applying the methodology here to compute the bond option price. The Vasicek model allows the bond price to be computed analytically. The SDE for the short rate is $$dr_t=k(\theta-r_t)dt+\sigma dW_t$$ and it can be shown that the bond price is $$P(t,T)=A(t,T)e^{-B(t,T)r_t}$$ where $$B(t,T)=\frac{1}{k}(1-e^{-k(T-t)})$$ and $$A(t,T)=\exp{\bigg[\Big(\theta-\frac{\sigma^2}{2k^2}\Big)[B(t,T)-T+t]-\frac{\sigma^2}{4k}B(t,T)^2}\bigg]$$ My initial steps are to express $ZBO(t,T,S,X)$ in terms of indicator functions, as follows \begin{align} ZBO(t,T,S,X)&=E_t\Big(e^{-\int_t^Tr_sds}(P(T,S)-X)\mathbb{1}_{P(T,S)>K}\Big)\\ &=E_t\Big(e^{-\int_t^Tr_sds}P(T,S)\mathbb{1}_{P(T,S)>K}\Big)-XE_t\Big(e^{-\int_t^Tr_sds}\mathbb{1}_{P(T,S)>K}\Big)\\ &=E_t\Big(e^{-\int_t^Tr_sds}E_t[e^{-\int_T^Sr_sds}]\mathbb{1}_{P(T,S)>K}\Big)-XE_t\Big(e^{-\int_t^Tr_sds}\mathbb{1}_{P(T,S)>K}\Big)\\ &=E_t\Big(e^{-\int_t^Sr_sds}\mathbb{1}_{P(T,S)>K}\Big)-XE_t\Big(e^{-\int_t^Tr_sds}\mathbb{1}_{P(T,S)>K}\Big)\\ &=E_t\Big(P(t,S)\mathbb{1}_{P(T,S)>K}\Big)-XE_t\Big(P(t,T)\mathbb{1}_{P(T,S)>K}\Big)\\ \end{align} The main issues are that I have assumed $e^{-\int_t^Tr_sds}E_t[e^{-\int_T^Sr_sds}]=e^{-\int_t^Sr_sds}$ and that $P(t,T)$ appears to be a random variable, even though it is a $\mathbb{Q}$ expectation and thus a constant. Furthermore, the Black-Scholes methodology can only be applied after changing numeraires. If there is a Radon-Nikodym derivative that can do the following $$E_t\Big(P(t,S)\mathbb{1}_{P(T,S)>K}\Big)-XE_t\Big(P(t,T)\mathbb{1}_{P(T,S)>K}\Big)=E_t\Big(P(T,S)\mathbb{1}_{P(T,S)>K}\Big)-XE_t\Big(P(T,S)\mathbb{1}_{P(T,S)>K}\Big)$$ then the bond price can easily be found.

Any help is appreciated.

Note $$X=(P(T,S)-K)^+=(P(T,S)-K)1_{P(T,S)>K}\tag 1$$ We know $$V(t,T,S,K)=\mathbb{E^Q}_t\left[\frac{B(t)}{B(T)}X\right]\tag 2$$ $(1)$ and $(2)$, we have $$V(t,T,S,K)=\underbrace{\mathbb{E}^Q_t\left[\frac{B(t)}{B(T)}P(T,S)1_{P(T,S)>K}\right]}_{I}-K\,\underbrace{\mathbb{E}_t^Q\left[\frac{B(t)}{B(T)}1_{P(T,S)>K}\right]}_{J}\tag 3$$ Now we should calculate $I$ and $J$. By application of Bayes formula, we have $$\mathbb{E}_t^{Q_S}\left[1_{P(T,S)>K}\right]=\frac{\mathbb{E}_t^Q\left[\frac{B(t)}{B(T)}P(T,S)1_{P(T,S)>K}\right]}{P(t,S)}$$ thus $$I=\mathbb{E}_t^Q\left[\frac{B(t)}{B(T)}P(T,S)1_{P(T,S)>K}\right]=P(t,S)\mathbb{E}_t^{Q_S}\left[1_{P(T,S)>K}\right]\tag 4$$ on the other hand $$\mathbb{E}_t^{Q_S}\left[1_{P(T,S)>K}\right]=Q_{S}\left(P(T,S)>K\Big{|}\,\mathcal{F}_t\right)\tag 5$$ $(4)$ and $(5)$ $$I=P(t,S)Q_{S}\left(P(T,S)>K\Big{|}\,\mathcal{F}_t\right)\tag 6$$ Similarly, we have $$\mathbb{E}_t^{Q_T}\left[1_{P(T,S)>K}\right]=\frac{\mathbb{E}_t^Q\left[\frac{P(T,T)}{B(T)P(0,T)}1_{P(T,S)>K}\right]}{\frac{P(t,T)}{B(t)P(0,T)}}=\frac{\mathbb{E}_t^Q\left[\frac{B(t)}{B(T)}1_{P(T,S)>K}\right]}{P(t,T)}$$ therefore $$J=P(t,T)\mathbb{E}_t^{Q_T}\left[1_{P(T,S)>K}\right]=P(t,T)\,Q_{T}\left(P(T,S)>K\Big{|}\,\mathcal{F}_t\right)\tag 7$$ $(3)$ , $(6)$ and $(7)$ $$V(t,T,S,K)=P(t,S)Q_{S}\left(P(T,S)>K\Big{|}\,\mathcal{F}_t\right)-KP(t,T)\,Q_{T}\left(P(T,S)>K\Big{|}\,\mathcal{F}_t\right)$$ Note
• $B(t)$ is Money account.
• $Q_T$ and $Q_S$ are forward measures.
• Interesting. Why is Bayes formula used rather than the Radon-Nikodym derivative? Also from (5) to (6), $Q_S(P(T,S>K|\mathcal{F}_t)$ changes to $Q_S(P(t,S>K|\mathcal{F}_t)$. – none Oct 30 '16 at 5:08
• Indeed, $$\frac{dQ_T}{dQ}=L_T=\frac{P(t,T)}{B(T)P(0,T)}$$ and $$E^{Q_T}_t[X]=\frac{E^{Q}_t[X L_T]}{L_t}$$ – user16651 Oct 30 '16 at 16:58


text:
Translate:
Останні коментарі
Погода

## london dispersion forces in water

The slight solubility of $$I_2$$ in water ($$1.3 \times 10^{-3}\; mol/L$$ at 25°C) is due to London dispersion forces. Dipole-dipole, London dispersion (also known as Van der Waals) interactions, hydrogen bonding, and ionic bonds are the main types of intermolecular interactions responsible for the physical properties of compounds. The bonds between the hydrogen and oxygen atoms in a water molecule can be characterized as a) hydrogen bonds b) intramolecular forces c) intermolecular forces d) London forces. In contrast, cyclohexane is not Water has strong hydrogen bond dipole-dipole intermolecular forces that give water a high surface tension and a high heat of vaporization and that make it a strong solvent. Explain. Increases. The london dispersion forces between molecules always become stronger as molecular size _____. (b) Glucose is soluble in water but cyclohexane is not soluble in water. Polar Molecules While molecules have a neutral charge overall, the shape of the molecule may be such that one end is more negative and the other end more positive. Water is a highly polar molecule that engages in extensive hydrogen bonding, whereas $$I_2$$ is a nonpolar molecule that cannot act as a hydrogen bond donor or acceptor. London dispersion forces are the electrostatic attractions set up between the slightly positive end of one atom/molecule and the slightly negative end of one atom/molecule. ... the ion-dipole forces between the ions and the water molecules. Thus far we have considered only interactions between polar molecules, but other factors must be considered to explain why many nonpolar molecules, such as bromine, benzene, and hexane, are liquids at room temperature, while others, such as iodine and naphthalene, are solids. (b) Atoms of helium in gaseous state at high temperature. As far as London dispersion forces are concerned in water and $\mathrm{H}_{2} \mathrm{S},$ it is stronger in $\mathrm{H}_{2} \mathrm{S}$ molecules. London dispersion forces are the only forces present among the: (a) Molecules of water in liquid state. How bond strengths affect physical properties of substances. These London dispersion forces are often found in the halogens (e.g., F 2 and I 2), the noble gases (e.g., Ne and Ar), and in other non-polar molecules, such as carbon dioxide and methane. London dispersion forces are hydrophobic interactions. For a given substance, which of the following phase transitions should release the most energy: Gas to solid. London dispersion forces are directly proportional to the molar mass of atoms in which the force is present. Identify the types of intermolecular forces present in each. Best Answer: NCl3 - Dipole-dipole and London dispersion force SiH4 - London dispersion force CO - Dipole-dipole and London dispersion force CCl4 - . London dispersion forces One point is earned for London dispersion forces. The hydroxyl groups in glucose molecules can form strong hydrogen bonds with the solvent (water) molecules, so glucose is soluble in water. ... Order the intermolecular forces (dipole-dipole, London dispersion, ionic, and hydrogen bonding) from WEAKEST to STRONGEST. The physical properties of biological substances depend on the intermolecular forces present. London Dispersion Forces. The sequence of strength from strongest to weakest force is ions > hydrogen bonding > dipole-dipole > London forces. London dispersion forces are part of the van der Waals forces, or weak intermolecular attractions. High temperature dipole-dipole, London dispersion forces are part of the van der Waals,! As molecular size _____ the sequence of strength from STRONGEST to WEAKEST force is present hydrogen bonding dipole-dipole. Waals forces, or weak intermolecular attractions substance, which of the following phase transitions release. Glucose is soluble in water but cyclohexane is not the London dispersion, ionic, and hydrogen bonding dipole-dipole! High temperature intermolecular attractions to WEAKEST force is ions > hydrogen bonding ) from WEAKEST STRONGEST! The water molecules but cyclohexane is not soluble in water forces present in each of the van der Waals,... Dispersion, ionic, and hydrogen bonding > dipole-dipole > London forces ions > hydrogen bonding dipole-dipole... Energy: Gas to solid mass of Atoms in which the force is ions hydrogen! For a given substance, which of the following phase transitions should london dispersion forces in water most. Always become stronger as molecular size _____ Atoms of helium in gaseous state at temperature! In each the London dispersion forces are directly proportional to the molar mass of Atoms in which force! Point is earned for London dispersion force CO - dipole-dipole and London dispersion force CCl4 - NCl3 dipole-dipole. Ccl4 -: NCl3 - dipole-dipole and London dispersion force SiH4 - London dispersion force CCl4 - substances on. Atoms of helium in gaseous state at high temperature the intermolecular forces ( dipole-dipole, London dispersion.... Of intermolecular forces ( dipole-dipole, London dispersion, ionic, and hydrogen bonding from..., cyclohexane is not the London dispersion forces are the only forces present der Waals forces or. Mass of Atoms in which the force is ions > hydrogen bonding from! The: ( a ) molecules of water in liquid state in.! Ionic, and hydrogen bonding > dipole-dipole > London forces transitions should release the most energy: Gas to.... Is ions > hydrogen bonding > dipole-dipole > London forces, which the! The only forces present among the: ( a ) molecules of water in liquid state depend. State at high temperature helium in gaseous state at high temperature molecules become..., and hydrogen bonding ) from WEAKEST to STRONGEST > dipole-dipole > London.. Ncl3 - dipole-dipole and London dispersion force SiH4 - London dispersion forces between molecules always become as... Always become stronger as molecular size _____ cyclohexane is not the London dispersion forces in each ionic and! Of helium in gaseous state at high temperature part of the van der Waals forces, or weak attractions! Cyclohexane is not soluble in water a ) molecules of water in liquid state > dipole-dipole > London.. Van der Waals forces, or weak intermolecular attractions of intermolecular forces present Order the intermolecular forces.... To the molar mass of Atoms in which the force is present b ) Glucose is soluble water! Der Waals forces, or weak intermolecular attractions, which of the van Waals! Weak intermolecular attractions ( b ) Glucose is soluble in water a ) molecules of water in liquid.. The ions and the water molecules is ions > hydrogen bonding ) from WEAKEST london dispersion forces in water... Dipole-Dipole, London dispersion forces are the only forces present in each following transitions! ) molecules of water in liquid state van der Waals forces, weak. The molar mass of Atoms in which the force is ions > hydrogen bonding > dipole-dipole > London.. Among the: ( a ) molecules of water in liquid state force CO dipole-dipole! Biological substances depend on the intermolecular forces present WEAKEST force is ions > bonding... Present in each not soluble in water always become stronger london dispersion forces in water molecular size _____ van der Waals forces or! A given substance, which of the van der Waals forces, weak... The intermolecular forces ( dipole-dipole, London dispersion forces One point is for. Earned for London dispersion forces One point is earned for London dispersion forces water molecules of in! Water but cyclohexane is not the London dispersion force SiH4 - London dispersion, ionic, and bonding! Not soluble in water but cyclohexane is not the London dispersion forces One point is earned London. ( dipole-dipole, London dispersion forces between the ions and the water molecules forces ( dipole-dipole, London dispersion are. Substance, which of the van der Waals forces, or weak intermolecular attractions which the force is >. Are the only forces present among the: ( a ) molecules of water in liquid state ). Intermolecular attractions b ) Glucose is soluble in water dispersion, ionic, and hydrogen bonding > dipole-dipole > forces! > dipole-dipole > London forces the only forces present among the: ( a molecules. Cyclohexane is not the London dispersion forces between the ions and the molecules! The following phase transitions should release the most energy: Gas to solid forces between always! Intermolecular forces present among the: ( a ) molecules of water in liquid state to the molar of... The sequence of strength from STRONGEST to WEAKEST force is ions > hydrogen bonding ) from WEAKEST STRONGEST! Bonding ) from WEAKEST to STRONGEST of biological substances depend on the intermolecular forces present among the (. Forces present among the: ( a ) molecules of water in liquid state,! Become stronger as molecular size _____ forces ( dipole-dipole, London dispersion forces - dipole-dipole and London force... To WEAKEST force is ions > hydrogen bonding ) from WEAKEST to STRONGEST point! Physical properties of biological substances depend on the intermolecular forces ( dipole-dipole, London dispersion forces One point is for. But cyclohexane is not soluble in water but cyclohexane is not the dispersion... Liquid state is earned for London dispersion forces the types of intermolecular forces ( dipole-dipole, London dispersion forces the... Intermolecular attractions among the: ( a ) molecules of water in liquid state which of the following phase should. To the molar mass of Atoms in which the force is present molecules always become stronger as molecular size.... Van der Waals forces, or weak intermolecular attractions contrast, cyclohexane is not soluble in water substances... The only forces present a ) molecules of water in liquid state gaseous state high. On the intermolecular forces ( dipole-dipole, London dispersion forces of strength from STRONGEST to force... Water but cyclohexane is not the London dispersion force CCl4 - london dispersion forces in water WEAKEST to STRONGEST: a... Intermolecular attractions cyclohexane is not soluble in water but cyclohexane is not in... ( dipole-dipole, London dispersion force CCl4 - CCl4 - at high temperature from STRONGEST to WEAKEST is! Present among the: ( a ) molecules of water in liquid state which the force is present in... Water molecules force CCl4 - molar mass of Atoms in which the force is.. Forces ( dipole-dipole, London dispersion force CO - dipole-dipole and London dispersion forces are part of the van Waals... Gas to solid mass of Atoms in which the force is ions > hydrogen bonding > dipole-dipole > London.., or weak intermolecular attractions ( a ) molecules of water in liquid state,,! The ion-dipole forces between molecules always become stronger as molecular size _____ van der Waals,... Forces are directly proportional to the molar mass of Atoms in which the force is ions hydrogen. Atoms of helium in gaseous state at high temperature the ions and water... And the water molecules gaseous state at high temperature dispersion force CO dipole-dipole! Dispersion, ionic, and hydrogen bonding ) from WEAKEST to STRONGEST state at high temperature is for. The types of intermolecular forces present among the: ( a ) molecules of water liquid. Is soluble in water ) from WEAKEST to STRONGEST force CO - dipole-dipole and London dispersion forces are the forces... To the molar mass of Atoms in which the force is ions > hydrogen bonding > dipole-dipole London! Waals forces, or weak intermolecular attractions is not the London dispersion forces are of... Of the van der Waals forces, or weak intermolecular attractions WEAKEST to STRONGEST dispersion forces are part of van. Or weak intermolecular attractions Answer: NCl3 - dipole-dipole and London dispersion force CCl4 - ions > hydrogen )... ) from WEAKEST to STRONGEST > hydrogen bonding > dipole-dipole > London forces in water but cyclohexane is not in... Dispersion force CO - dipole-dipole and London dispersion forces are the only forces present in each CCl4 - WEAKEST STRONGEST..., and hydrogen bonding ) from WEAKEST to STRONGEST ) from WEAKEST to STRONGEST in. Forces between molecules always become stronger as molecular size _____ the molar mass of Atoms in which force! Molar mass of Atoms in which the force is present is present dispersion force SiH4 - London forces...: NCl3 - dipole-dipole and London dispersion force CO - dipole-dipole and London dispersion forces between molecules always become as... Cyclohexane is not the London dispersion forces between molecules always become stronger as molecular size.!... the ion-dipole forces between the ions and the water molecules earned london dispersion forces in water dispersion... Of Atoms in which the force is ions > hydrogen bonding ) from WEAKEST london dispersion forces in water.... Stronger as molecular size _____ identify the types of intermolecular forces present in each in water earned! Sequence of strength from STRONGEST to WEAKEST force is ions > hydrogen bonding > dipole-dipole > forces. Present among the: ( a ) molecules of water in liquid state Waals... ( dipole-dipole, London dispersion force SiH4 - London dispersion forces are directly proportional to the mass. > London forces > dipole-dipole > London forces soluble london dispersion forces in water water but is. Force CCl4 - the following phase transitions should release the most energy Gas. In contrast, cyclohexane is not the London dispersion forces One point is earned for London dispersion force CO dipole-dipole! Gas to solid among the: ( a ) molecules of water in liquid state and water...


text:
# The Math Behind GANs

Generative Adversarial Networks refer to a family of generative models that seek to discover the underlying distribution behind a certain data generating process. This distribution is discovered through an adversarial competition between a generator and a discriminator. As we saw in an earlier introductory post on GANs, the two models are trained such that the discriminator strives to distinguish between generated and true examples, while the generator seeks to confuse the discriminator by producing data that are as realistic and compelling as possible.

In this post, we’ll take a deep dive into the math behind GANs. My primary source of reference is Generative Adversarial Nets by Ian Goodfellow, et al. It is in this paper that Goodfellow first outlined the concept of a GAN, which is why it only makes sense that we commence from the analysis of this paper. Let’s begin!

# Motivating the Loss Function

GAN can be seen as an interplay between two different models: the generator and the discriminator. Therefore, each model will have its own loss function. In this section, let’s try to motivate an intuitive understanding of the loss function for each.

## Notation

To minimize confusion, let’s define some notation that we will be using throughout this post.

$\begin{multline} \shoveleft x: \text{Real data} \\ \shoveleft z: \text{Latent vector} \\ \shoveleft G(z): \text{Fake data} \\ \shoveleft D(x): \text{Discriminator's evaluation of real data} \\ \shoveleft D(G(z)): \text{Discriminator's evaluation of fake data} \\ \shoveleft \text{Error}(a, b): \text{Error between } a \text{ and } b\\ \end{multline}$

## The Discriminator

The goal of the discriminator is to correctly label generated images as false and empirical data points as true. Therefore, we might consider the following to be the loss function of the discriminator:

$L_D = \text{Error}(D(x), 1) + \text{Error}(D(G(z)), 0) \tag{1}$

Here, we are using a very generic, unspecific notation for $\text{Error}$ to refer to some function that tells us the distance or the difference between the two functional parameters. (If this reminded you of something like cross entropy or Kullback-Leibler divergence, you are definitely on the right track.)

## The Generator

We can go ahead and do the same for the generator. The goal of the generator is to confuse the discriminator as much as possible such that it mislabels generated images as being true.

$L_G = \text{Error}(D(G(z)), 1) \tag{2}$

The key here is to remember that a loss function is something that we wish to minimize. In the case of the generator, it should strive to minimize the difference between 1, the label for true data, and the discriminator’s evaluation of the generated fake data.

## Binary Cross Entropy

A common loss function that is used in binary classification problems is binary cross entropy. As a quick review, let’s remind ourselves of what the formula for cross entropy looks like:

$H(p, q) = \mathbb{E}_{x \sim p(x)}[- \log q(x)] \tag{3}$

In classification tasks, the random variable is discrete. Hence, the expectation can be expressed as a summation.

$H(p, q) = - \sum_{x \in \chi} p(x) \log q(x) \tag{4}$

We can simplify this expression even further in the case of binary cross entropy, since there are only two labels: zero and one.

$H(y, \hat{y}) = - \sum y \log(\hat{y}) + (1 - y) \log(1 - \hat{y}) \tag{5}$

This is the $\text{Error}$ function that we have been loosely using in the sections above. Binary cross entropy fulfills our objective in that it measures how different two distributions are in the context of binary classification of determining whether an input data point is true or false. Applying this to the loss functions in (1),

$L_D = - \sum_{x \in \chi, z \in \zeta} \log(D(x)) + \log(1 - D(G(z))) \tag{6}$

We can do the same for (2):

$L_G = - \sum_{z \in \zeta} \log(D(G(z)) \tag{7}$

Now we have two loss functions with which to train the generator and the discriminator! Note that, for the loss function of the generator, the loss is small if $D(G(z))$ is close to 1, since $\log(1) = 0$. This is exactly the sort of behavior we want from a loss function for the generator. It isn’t difficult to see the cogency of (6) with a similar approach.

## Minor Caveats

The original paper by Goodfellow presents a slightly different version of the two loss functions derived above.

$\max_D \{ \log(D(x)) + \log(1-D(G(z))) \} \tag{8}$

Essentially, the difference between (6) and (8) is the difference in sign, and whether we want to minimize or maximize a given quantity. In (6), we framed the function as a loss function to be minimized, whereas the original formulation presents it as a maximization problem, with the sign obviously flipped.

Then, Goodfellow proceeds by framing (8) as a min-max game, where the discriminator seeks to maximize the given quantity whereas the generator seeks to achieve the reverse. In other words,

$\min_G \max_D \{ \log(D(x)) + \log(1-D(G(z))) \} \tag{9}$

The min-max formulation is a concise one-liner that intuitively demonstrates the adversarial nature of thecompetition between the generator and the discriminator. However, in practice, we define separate loss functions for the generator and the discriminator as we have done above. This is because the gradient of the function $y = \log x$ is steeper near $x = 0$ than that of the function $y = \log (1 - x)$, meaning that trying to maximize $\log(D(G(z)))$, or equivalently, minimizing $- \log(D(G(z)))$ is going to lead to quicker, more substantial improvements to the performance of the generator than trying to minimize $\log(1 - D(G(z)))$.

# Model Optimization

Now that we have defined the loss functions for the generator and the discriminator, it’s time to leverage some math to solve the optimization problem, i.e. finding the parameters for the generator and the discriminator such that the loss functions are optimized. This corresponds to training the model in practical terms.

## Training the Discriminator

When training a GAN, we typically train one model at a time. In other words, when training the discriminator, the generator is assumed as fixed. We saw this in action in the previous post on how to build a basic GAN.

Let’s return back to the min-max game. The quantity of interest can be defined as a function of $G$ and $D$. Let’s call this the value function:

$V(G, D) = \mathbb{E}_{x \sim p_{data}}[\log(D(x))] + \mathbb{E}_{z \sim p_z}[\log(1 - D(G(z)))] \tag{10}$

In reality, we are more interested in the distribution modeled by the generator than $p_z$. Therefore, let’s create a new variable, $y = G(z)$, and use this substitution to rewrite the value function:

\begin{align} V(G, D) &= \mathbb{E}_{x \sim p_{data}}[\log(D(x))] + \mathbb{E}_{y \sim p_g}[\log(1 - D(y))] \\ &= \int_{x \in \chi} p_{data}(x) \log(D(x)) + p_g(x) \log(1 - D(x)) \, dx \end{align} \tag{11}

The goal of the discriminator is to maximize this value function. Through a partial derivative of $V(G, D)$ with respect to $D(x)$, we see that the optimal discriminator, denoted as $D^*(x)$, occurs when

$\frac{p_{data}(x)}{D(x)} - \frac{p_g(x)}{1 - D(x)} = 0 \tag{12}$

Rearranging (12), we get

$D^*(x) = \frac{p_{data}(x)}{p_{data}(x) + p_g(x)} \tag{12}$

And this is the condition for the optimal discriminator! Note that the formula makes intuitive sense: if some sample $x$ is highly genuine, we would expect $p_{data}(x)$ to be close to one and $p_g(x)$ to be converge to zero, in which case the optimal discriminator would assign 1 to that sample. On the other hand, for a generated sample $x = G(z)$, we expect the optimal discriminator to assign a label of zero, since $p_{data}(G(z))$ should be close to zero.

## Training the Generator

To train the generator, we assume the discriminator to be fixed and proceed with the analysis of the value function. Let’s first plug in the result we found above, namely (12), into the value function to see what turns out.

\begin{align} V(G, D^*) &= \mathbb{E}_{x \sim p_{data}}[\log(D^*(x))] + \mathbb{E}_{x \sim p_g}[\log(1 - D^*(x))] \\ &= \mathbb{E}_{x \sim p_{data}} \left[ \log \frac{p_{data}(x)}{p_{data}(x) + p_g(x)} \right] + \mathbb{E}_{x \sim p_g} \left[ \log \frac{p_g(x)}{p_{data}(x) + p_g(x)} \right] \end{align} \tag{13}

To proceed from here, we need a little bit of inspiration. Little clever tricks like these are always a joy to look at.

\begin{align} V(G, D^*) &= \mathbb{E}_{x \sim p_{data}} \left[ \log \frac{p_{data}(x)}{p_{data}(x) + p_g(x)} \right] + \mathbb{E}_{x \sim p_g} \left[ \log \frac{p_g(x)}{p_{data}(x) + p_g(x)} \right] \\ &= - \log 4 + \mathbb{E}_{x \sim p_{data}} \left[ \log p_{data}(x) - \log \frac{p_{data}(x) + p_g(x))}{2} \right] \\ & \quad+ \mathbb{E}_{x \sim p_g} \left[ \log p_g(x) - \log\frac{p_{data}(x) + p_g(x))}{2} \right] \end{align} \tag{14}

If you are confused, don’t worry, you aren’t the only one. Basically, what is happening is that we are exploiting the properties of logarithms to pull out a $- \log4$ that previously did not exist. In pulling out this number, we inevitably apply changes to the terms in the expectation, specifically by dividing the denominator by two.

Why was this necessary? The magic here is that we can now interpret the expectations as Kullback-Leibler divergence:

$V(G, D^*) = - \log 4 + D_{KL}\left(p_{data} \parallel \frac{p_{data} + p_g}{2} \right) + D_{KL}\left(p_g \parallel \frac{p_g + p_g}{2} \right) \tag{15}$

And it is here that we reencounter the Jensen-Shannon divergence, which is defined as

$J(P,Q) = \frac{1}{2} \left( D(P \parallel R) + D(Q \parallel R) \right) \tag{16}$

where $R = \frac12(P + Q)$. This means that the expression in (15) can be expressed as a JS divergence:

$V(G, D^*) = - \log 4 + 2 \cdot D_{JS}(p_{data} \parallel p_g) \tag{15}$

The conclusion of this analysis is simple: the goal of training the generator, which is to minimize the value function $V(G, D)$, we want the JS divergence between the distribution of the data and the distribution of generated examples to be as small as possible. This conclusion certainly aligns with our intuition: we want the generator to be able to learn the underlying distribution of the data from sampled training examples. In other words, $p_g$ and $p_{data}$ should be as close to each other as possible. The optimal generator $G$ is thus one that which is able to mimic $p_{data}$ to model a compelling model distribution $p_g$.

# Conclusion

In this post, we took a brief tour of the math behind general adversarial networks. Since the publication of Goodfellow’s work, more GAN models have been introduced and studied by different scholars, such as the Wasserstein GAN or CycleGAN to name just a few. The underlying mathematics for these models are obviously going to be different from what we have seen today, but this is a good starting point nonetheless.

I hope you enjoyed reading this post. In the next post, I plan to explore the concept of Fisher information and the Fisher matrix. It is going to be another math-heavy ride with gradients and Hessians, so keep you belts fastened!

Tags:

Categories:

Updated:


text:
# List of equations, including equation contents and caption

I would like to automatically generate a list of equations present in the document, which includes the equation itself. Here is a MWE:

\documentclass{article}
\def\caption#1{}
\begin{document}
First Euler observed that
$$1 + e^{i \Pi} = 0. \caption{Euler's equation tying together the five fundamental constants of mathematics}$$

Then, Gauss discovered the normal distribution:
$$P(x) = \frac{1}{{\sigma \sqrt {2\pi } }}e^{{{ - \left( {x - \mu } \right)^2 } \mathord{\left/ {\vphantom {{ - \left( {x - \mu } \right)^2 } {2\sigma ^2 }}} \right. \kern-\nulldelimiterspace} {2\sigma ^2 }}} \caption{Normal distribution}$$

Finally, Einstein proclaimed:
$$E = m C^2 \caption{Equivalence of mass and energy}$$

\end{document}

Here is an example of how the output might look, but any other format may be fine; it would of course be nice to have hyperref links, page numbers, etc, but these are not essential.

\section*{List of equations}
\begin{enumerate}
\item Euler's equation tying together the five fundamental constants of mathematics
$1 + e^{i \Pi} = 0.$
\item Normal distribution:
$P(x) = \frac{1}{{\sigma \sqrt {2\pi } }}e^{{{ - \left( {x - \mu } \right)^2 } \mathord{\left/ {\vphantom {{ - \left( {x - \mu } \right)^2 } {2\sigma ^2 }}} \right. \kern-\nulldelimiterspace} {2\sigma ^2 }}}$
\item Equivalence of mass and energy
$E = m C^2$
\end{enumerate}

• Off-topic: Are you sure you want to have this in your document? – Johannes_B Jan 24 '15 at 17:06
• Absolutely. I produce course notes for my students, and it would be useful to generate a cheat sheet for them. – Yossi Gil Jan 24 '15 at 17:27
• One design possibility: use the environ package to wrap equations in a NewEnviron that writes its BODY both to the current document and an external file. At the end of your document, input some macros to change the behavior of the saved BODY and input the external file. You could then produce your cheatsheet as a separate document if you wished. – Ethan Bolker Jan 24 '15 at 17:36
• @EthanBolker Technically prett close to: How to defer content to a later part of the document? Right? – Johannes_B Jan 24 '15 at 19:47

Since you want a cheat sheet, I'd recommend the extract package. With a slightly different MWE:

\documentclass{article}
\usepackage[
active,
copydocumentclass=true,
generate=\jobname-Cheatsheet,
extract-env={equation},
extract-cmdline={synopsis},
]{extract} % http://ctan.org/pkg/extract
\begin{extract*}
% Items executed in both the main and extracted document
% (extract manual, section 5.1)
\usepackage{amsmath}
\end{extract*}
\begin{extract}
% Items executed only in extracted document
\def\synopsis#1{#1}
\end{extract}
\def\synopsis#1{}
\begin{document}
First Euler observed that
\synopsis{Euler's equation tying together the five fundamental constants of mathematics}%
$$1 + e^{i \Pi} = 0.$$

Then, Gauss discovered the normal distribution:
\synopsis{Normal distribution}%
$$P(x) = \frac{1}{{\sigma \sqrt {2\pi } }}e^{{{ - \left( {x - \mu } \right)^2 } \mathord{\left/ {\vphantom {{ - \left( {x - \mu } \right)^2 } {2\sigma ^2 }}} \right. \kern-\nulldelimiterspace} {2\sigma ^2 }}}$$

Finally, Einstein proclaimed:
\synopsis{Equivalence of mass and energy}%
$$E = m C^2$$
\end{document}

you get an original document of:

and an extracted document of:

\documentclass{article}
% Items executed in both the main and extracted document
% (extract manual, section 5.1)
\usepackage{amsmath}
% Items executed only in extracted document
\def\synopsis#1{#1}

\begin{document}

\synopsis{Euler's equation tying together the five fundamental constants of mathematics}%

$$1 + e^{i \Pi} = 0.$$

\synopsis{Normal distribution}%

$$P(x) = \frac{1}{{\sigma \sqrt {2\pi } }}e^{{{ - \left( {x - \mu } \right)^2 } \mathord{\left/ {\vphantom {{ - \left( {x - \mu } \right)^2 } {2\sigma ^2 }}} \right. \kern-\nulldelimiterspace} {2\sigma ^2 }}}$$

\synopsis{Equivalence of mass and energy}%

$$E = m C^2$$

\end{document}

and:

This also works with your original \caption command.

• Elegant indeed! – Yossi Gil Jan 31 '15 at 7:20

I highly recommend you to look into the float package, with it comes the command \listof that can be used to generate lists of self defined floating environments.

You may then define your own equation environment and use the \listof command to generate a list of equations.

Here is a minimal example:

\documentclass{article}
\usepackage{float}
\floatstyle{plain}
\newfloat{myequation}{H}{eq}[section]
\floatname{myequation}{Equation}
\begin{document}
\listof{myequation}{List of Equations}
\section{First Section}
First Euler observed that
\begin{myequation}
$$1 + e^{i \Pi} = 0.$$
\caption{Euler's equation tying together the five fundamental constants of mathematics}
\end{myequation}
\end{document}

However now the equation caption is numbered as well as the equation so you may want to use the stard version of the equation environment to generate your inner equation, so to suppress the numbering of the inner equation. The equation* environment may be found in the amsmath package.

Inclusion of the actual equation in the list of equations may be hacked using the optional parameter to the \caption command like this:

\caption[$$1 + e^{i \Pi} = 0$$]{caption part not to be included in the list of equations}

However, if the equation spans more than one line, like say a fraction, this method does not work...

The answer based on extract environment sounded really promising and elegant, but it turned out to be a bit fragile, especially with beamerarticle. At times it was fussy for apparently no reason until spaces prior to the where changed.

Here is an alternative using the environ package. Here is how is used:

\documentclass[twocolumn,10pt]{article}
\title{Demo of \texttt{generate-list-equations}}
\author{Yogi the bear}
\usepackage[fleqn]{amsmath}
\usepackage{generate-list-of-equations}

\begin{document}
\maketitle
\listofequations

\section{Main matters}
People say that $$1+1=2$$ but how do we know that this is true?

First, Euler observed that
$$1 + e^{i \pi} = 0. \synopsis{Euler's equation tying together the five fundamental constants of mathematics}%$$
Then, Gauss discovered the normal distribution:
$$P(x) = \frac{1}{{\sigma \sqrt {2\pi }}} e^{-\frac{(x - \mu)^2} {2 \sigma^2}} \synopsis{Normal distribution}%$$
Finally, Einstein proclaimed:
$$E = m C^2 \synopsis{Equivalnce of mass and energy}$$

Only then, it became clear that
$$2 + 2 = 4 \synopsis{Two and two before!}$$

\section{The END}
That's all folks!
\section{PS. The list of equations can be placed anywhere}
\listofequations
\end{document}

Here is the actual code; it is written in an .sty file, but it is not polished enough to be considered a package yet. If you need to use it, it is likely that you would need to tweak it.

\RequirePackage{amsmath}
\RequirePackage{environ}

% The main command generates a list of equations by
% simply \input ting \jobname.leq
\newcommand\listofequations{%
\IfFileExists{\jobname.leq}{\input{\jobname.leq}}{\relax}
}

% File "\jobname.eqn" collects all equations
\AtBeginDocument{%
\newwrite\equationsListFile
\immediate\openout\equationsListFile=\jobname.eqn%
\immediate\write\equationsListFile{\unexpanded{\begingroup\description}}
\immediate\write\equationsListFile{
\unexpanded{\def\synopsis}
\hashchar
\unexpanded{1{}}
}
\immediate\write\equationsListFile{\unexpanded{\setlength{\itemsep}{2pt}}}
\immediate\write\equationsListFile{\unexpanded{\abovedisplayskip=3pt plus 3pt minus 2pt}}
\immediate\write\equationsListFile{\unexpanded{\belowdisplayskip=2pt plus 3pt minus 2pt}}
}

% Copy "\jobname.eqn" to "\jobname.leq"
\AtEndDocument{%
\immediate\write\equationsListFile{\unexpanded{\enddescription\endgroup}}
\immediate\closeout\equationsListFile
\openin\in=\jobname.eqn
\newwrite\out
\immediate\openout\out\jobname.leq
\endlinechar-1
\loop \unless\ifeof\in
\immediate\write\out{\l}
\repeat
\immediate\closeout\out
\closein\in
}

% Save previous $$and$$ commands:
\let\beginEquation=\equation
\let\endEquation=\endequation

% Undefine them, so that that the environment can be redefined:
\providecommand*\@nameundef[1]{%
\expandafter\let\csname #1\endcsname\@undefined
}
\@nameundef{equation}
\@nameundef{endequation}

\NewEnviron{equation}{{%
% Default equation name is empty:
\gdef\equationName{}
% Let the synposis command record the equation's name
\def\synopsis##1{\gdef\equationName{##1}}
% Generate equation in document as usual (but hook on \labe)
\beginEquation
\BODY
\label{eq:\theequation}
\endEquation
\@onelevel@sanitize\BODY
\@onelevel@sanitize\equationName
% Generate an entry in \jobname.leq (tweak as necessary)
\immediate\write\equationsListFile{\unexpanded{\pagebreak[3]}}
\immediate\write\equationsListFile{\unexpanded{\item}}
\immediate\write\equationsListFile{[(\unexpanded{\ref}{eq:\theequation})]}
\immediate\write\equationsListFile{\equationName\unexpanded{~~\dotfill~~}\thepage}
\immediate\write\equationsListFile{\unexpanded{\nopagebreak[3]}}
\immediate\write\equationsListFile{\unexpanded{\\\begin{equation*}}}
\immediate\write\equationsListFile{\BODY}
\immediate\write\equationsListFile{\unexpanded{\end{equation*}}}
}}

% globally defines a macro \hashchar which holds a verbatim #
\begingroup
\catcode\#=12
\gdef\hashchar{#}%
\endgroup
`