text:
Main Content

# Train Variational Autoencoder (VAE) to Generate Images

This example shows how to create a variational autoencoder (VAE) in MATLAB to generate digit images. The VAE generates hand-drawn digits in the style of the MNIST data set.

VAEs differ from regular autoencoders in that they do not use the encoding-decoding process to reconstruct an input. Instead, they impose a probability distribution on the latent space, and learn the distribution so that the distribution of outputs from the decoder matches that of the observed data. Then, they sample from this distribution to generate new data.

In this example, you construct a VAE network, train it on the MNIST data set, and generate new images that closely resemble those in the data set.

### Load Data

Download the MNIST files from http://yann.lecun.com/exdb/mnist/ and load the MNIST data set into the workspace [1]. Call the `processImagesMNIST` and `processLabelsMNIST` helper functions attached to this example to load the data from the files into MATLAB arrays.

Because the VAE compares the reconstructed digits against the inputs and not against the categorical labels, you do not need to use the training labels in the MNIST data set.

```trainImagesFile = 'train-images-idx3-ubyte.gz'; testImagesFile = 't10k-images-idx3-ubyte.gz'; testLabelsFile = 't10k-labels-idx1-ubyte.gz'; XTrain = processImagesMNIST(trainImagesFile);```
```Read MNIST image data... Number of images in the dataset: 60000 ... ```
```numTrainImages = size(XTrain,4); XTest = processImagesMNIST(testImagesFile);```
```Read MNIST image data... Number of images in the dataset: 10000 ... ```
`YTest = processLabelsMNIST(testLabelsFile);`
```Read MNIST label data... Number of labels in the dataset: 10000 ... ```

### Construct Network

Autoencoders have two parts: the encoder and the decoder. The encoder takes an image input and outputs a compressed representation (the encoding), which is a vector of size `latentDim`, equal to 20 in this example. The decoder takes the compressed representation, decodes it, and recreates the original image.

To make calculations more numerically stable, increase the range of possible values from [0,1] to [-inf, 0] by making the network learn from the logarithm of the variances. Define two vectors of size `latent_dim`: one for the means $\mu$ and one for the logarithm of the variances $\mathrm{log}\left({\sigma }^{2}\right)$. Then use these two vectors to create the distribution to sample from.

Use 2-D convolutions followed by a fully connected layer to downsample from the 28-by-28-by-1 MNIST image to the encoding in the latent space. Then, use transposed 2-D convolutions to scale up the 1-by-1-by-20 encoding back into a 28-by-28-by-1 image.

```latentDim = 20; imageSize = [28 28 1]; encoderLG = layerGraph([ imageInputLayer(imageSize,'Name','input_encoder','Normalization','none') convolution2dLayer(3, 32, 'Padding','same', 'Stride', 2, 'Name', 'conv1') reluLayer('Name','relu1') convolution2dLayer(3, 64, 'Padding','same', 'Stride', 2, 'Name', 'conv2') reluLayer('Name','relu2') fullyConnectedLayer(2 * latentDim, 'Name', 'fc_encoder') ]); decoderLG = layerGraph([ imageInputLayer([1 1 latentDim],'Name','i','Normalization','none') transposedConv2dLayer(7, 64, 'Cropping', 'same', 'Stride', 7, 'Name', 'transpose1') reluLayer('Name','relu1') transposedConv2dLayer(3, 64, 'Cropping', 'same', 'Stride', 2, 'Name', 'transpose2') reluLayer('Name','relu2') transposedConv2dLayer(3, 32, 'Cropping', 'same', 'Stride', 2, 'Name', 'transpose3') reluLayer('Name','relu3') transposedConv2dLayer(3, 1, 'Cropping', 'same', 'Name', 'transpose4') ]);```

To train both networks with a custom training loop and enable automatic differentiation, convert the layer graphs to `dlnetwork` objects.

```encoderNet = dlnetwork(encoderLG); decoderNet = dlnetwork(decoderLG);```

### Define Model Gradients Function

The helper function modelGradients takes in the encoder and decoder `dlnetwork` objects and a mini-batch of input data `X`, and returns the gradients of the loss with respect to the learnable parameters in the networks. This helper function is defined at the end of this example.

The function performs this process in two steps: sampling and loss. The sampling step samples the mean and the variance vectors to create the final encoding to be passed to the decoder network. However, because backpropagation through a random sampling operation is not possible, you must use the reparameterization trick. This trick moves the random sampling operation to an auxiliary variable $\epsilon$, which is then shifted by the mean ${\mu }_{\mathit{i}}$ and scaled by the standard deviation ${\sigma }_{\mathit{i}}$. The idea is that sampling from $\mathit{N}\left({\mu }_{\mathit{i}},{\sigma }_{\mathit{i}}^{2}\right)$ is the same as sampling from ${\mu }_{\mathit{i}}+\epsilon \cdot {\sigma }_{\mathit{i}}$, where $\epsilon \sim \mathit{N}\left(0,1\right)$. The following figure depicts this idea graphically.

The loss step passes the encoding generated by the sampling step through the decoder network, and determines the loss, which is then used to compute the gradients. The loss in VAEs, also called the evidence lower bound (ELBO) loss, is defined as a sum of two separate loss terms:

$\mathrm{ELBO}\text{\hspace{0.17em}}\mathrm{loss}=\mathrm{reconstruction}\text{\hspace{0.17em}}\mathrm{loss}+\mathrm{KL}\text{\hspace{0.17em}}\mathrm{loss}$.

The reconstruction loss measures how close the decoder output is to the original input by using the mean-squared error (MSE):

$\mathrm{reconstruction}\text{\hspace{0.17em}}\mathrm{loss}=\mathrm{MSE}\left(\mathrm{decoder}\text{\hspace{0.17em}}\mathrm{output},\mathrm{original}\text{\hspace{0.17em}}\mathrm{image}\right)$.

The KL loss, or Kullback–Leibler divergence, measures the difference between two probability distributions. Minimizing the KL loss in this case means ensuring that the learned means and variances are as close as possible to those of the target (normal) distribution. For a latent dimension of size $\mathit{n}$, the KL loss is obtained as

$\mathrm{KL}\text{\hspace{0.17em}}\mathrm{loss}=-0.5\cdot \sum _{\mathit{i}=1}^{\mathit{n}}\left(1+\mathrm{log}\left({\sigma }_{\mathit{i}}^{2}\right)-{\mu }_{\mathit{i}}^{2}-{\sigma }_{\mathit{i}}^{2}\right)$.

The practical effect of including a KL loss term is to pack the clusters learned due to the reconstruction loss tightly around the center of the latent space, forming a continuous space to sample from.

### Specify Training Options

Train on a GPU if one is available (requires Parallel Computing Toolbox™).

`executionEnvironment = "auto";`

Set the training options for the network. When using the Adam optimizer, you need to initialize for each network the trailing average gradient and the trailing average gradient-square decay rates with empty arrays`.`

```numEpochs = 50; miniBatchSize = 512; lr = 1e-3; numIterations = floor(numTrainImages/miniBatchSize); iteration = 0; avgGradientsEncoder = []; avgGradientsSquaredEncoder = []; avgGradientsDecoder = []; avgGradientsSquaredDecoder = [];```

### Train Model

Train the model using a custom training loop.

For each iteration in an epoch:

• Obtain the next mini-batch from the training set.

• Convert the mini-batch to a `dlarray` object, making sure to specify the dimension labels `'SSCB'` (spatial, spatial, channel, batch).

• For GPU training, convert the `dlarray` to a `gpuArray` object.

• Evaluate the model gradients using the `dlfeval `and` modelGradients `functions.

• Update the network learnables and the average gradients for both networks, using the `adamupdate` function.

At the end of each epoch, pass the test set images through the autoencoder, and display the loss and the training time for that epoch.

```for epoch = 1:numEpochs tic; for i = 1:numIterations iteration = iteration + 1; idx = (i-1)*miniBatchSize+1:i*miniBatchSize; XBatch = XTrain(:,:,:,idx); XBatch = dlarray(single(XBatch), 'SSCB'); if (executionEnvironment == "auto" && canUseGPU) || executionEnvironment == "gpu" XBatch = gpuArray(XBatch); end [infGrad, genGrad] = dlfeval(... @modelGradients, encoderNet, decoderNet, XBatch); [decoderNet.Learnables, avgGradientsDecoder, avgGradientsSquaredDecoder] = ... adamupdate(decoderNet.Learnables, ... genGrad, avgGradientsDecoder, avgGradientsSquaredDecoder, iteration, lr); [encoderNet.Learnables, avgGradientsEncoder, avgGradientsSquaredEncoder] = ... adamupdate(encoderNet.Learnables, ... infGrad, avgGradientsEncoder, avgGradientsSquaredEncoder, iteration, lr); end elapsedTime = toc; [z, zMean, zLogvar] = sampling(encoderNet, XTest); xPred = sigmoid(forward(decoderNet, z)); elbo = ELBOloss(XTest, xPred, zMean, zLogvar); disp("Epoch : "+epoch+" Test ELBO loss = "+gather(extractdata(elbo))+... ". Time taken for epoch = "+ elapsedTime + "s") end```
```Epoch : 1 Test ELBO loss = 28.0145. Time taken for epoch = 28.0573s Epoch : 2 Test ELBO loss = 24.8995. Time taken for epoch = 8.797s Epoch : 3 Test ELBO loss = 23.2756. Time taken for epoch = 8.8824s Epoch : 4 Test ELBO loss = 21.151. Time taken for epoch = 8.5979s Epoch : 5 Test ELBO loss = 20.5335. Time taken for epoch = 8.8472s Epoch : 6 Test ELBO loss = 20.232. Time taken for epoch = 8.5068s Epoch : 7 Test ELBO loss = 19.9988. Time taken for epoch = 8.4356s Epoch : 8 Test ELBO loss = 19.8955. Time taken for epoch = 8.4015s Epoch : 9 Test ELBO loss = 19.7991. Time taken for epoch = 8.8089s Epoch : 10 Test ELBO loss = 19.6773. Time taken for epoch = 8.4269s Epoch : 11 Test ELBO loss = 19.5181. Time taken for epoch = 8.5771s Epoch : 12 Test ELBO loss = 19.4532. Time taken for epoch = 8.4227s Epoch : 13 Test ELBO loss = 19.3771. Time taken for epoch = 8.5807s Epoch : 14 Test ELBO loss = 19.2893. Time taken for epoch = 8.574s Epoch : 15 Test ELBO loss = 19.1641. Time taken for epoch = 8.6434s Epoch : 16 Test ELBO loss = 19.2175. Time taken for epoch = 8.8641s Epoch : 17 Test ELBO loss = 19.158. Time taken for epoch = 9.1083s Epoch : 18 Test ELBO loss = 19.085. Time taken for epoch = 8.6674s Epoch : 19 Test ELBO loss = 19.1169. Time taken for epoch = 8.6357s Epoch : 20 Test ELBO loss = 19.0791. Time taken for epoch = 8.5512s Epoch : 21 Test ELBO loss = 19.0395. Time taken for epoch = 8.4674s Epoch : 22 Test ELBO loss = 18.9556. Time taken for epoch = 8.3943s Epoch : 23 Test ELBO loss = 18.9469. Time taken for epoch = 10.2924s Epoch : 24 Test ELBO loss = 18.924. Time taken for epoch = 9.8302s Epoch : 25 Test ELBO loss = 18.9124. Time taken for epoch = 9.9603s Epoch : 26 Test ELBO loss = 18.9595. Time taken for epoch = 10.9887s Epoch : 27 Test ELBO loss = 18.9256. Time taken for epoch = 10.1402s Epoch : 28 Test ELBO loss = 18.8708. Time taken for epoch = 9.9109s Epoch : 29 Test ELBO loss = 18.8602. Time taken for epoch = 10.3075s Epoch : 30 Test ELBO loss = 18.8563. Time taken for epoch = 10.474s Epoch : 31 Test ELBO loss = 18.8127. Time taken for epoch = 9.8779s Epoch : 32 Test ELBO loss = 18.7989. Time taken for epoch = 9.6963s Epoch : 33 Test ELBO loss = 18.8. Time taken for epoch = 9.8848s Epoch : 34 Test ELBO loss = 18.8095. Time taken for epoch = 10.3168s Epoch : 35 Test ELBO loss = 18.7601. Time taken for epoch = 10.8058s Epoch : 36 Test ELBO loss = 18.7469. Time taken for epoch = 9.9365s Epoch : 37 Test ELBO loss = 18.7049. Time taken for epoch = 10.0343s Epoch : 38 Test ELBO loss = 18.7084. Time taken for epoch = 10.3214s Epoch : 39 Test ELBO loss = 18.6858. Time taken for epoch = 10.3985s Epoch : 40 Test ELBO loss = 18.7284. Time taken for epoch = 10.9685s Epoch : 41 Test ELBO loss = 18.6574. Time taken for epoch = 10.5241s Epoch : 42 Test ELBO loss = 18.6388. Time taken for epoch = 10.2392s Epoch : 43 Test ELBO loss = 18.7133. Time taken for epoch = 9.8177s Epoch : 44 Test ELBO loss = 18.6846. Time taken for epoch = 9.6858s Epoch : 45 Test ELBO loss = 18.6001. Time taken for epoch = 9.5588s Epoch : 46 Test ELBO loss = 18.5897. Time taken for epoch = 10.4554s Epoch : 47 Test ELBO loss = 18.6184. Time taken for epoch = 10.0317s Epoch : 48 Test ELBO loss = 18.6389. Time taken for epoch = 10.311s Epoch : 49 Test ELBO loss = 18.5918. Time taken for epoch = 10.4506s Epoch : 50 Test ELBO loss = 18.5081. Time taken for epoch = 9.9671s ```

### Visualize Results

To visualize and interpret the results, use the helper Visualization functions. These helper functions are defined at the end of this example.

The `VisualizeReconstruction` function shows a randomly chosen digit from each class accompanied by its reconstruction after passing through the autoencoder.

The `VisualizeLatentSpace` function takes the mean and the variance encodings (each of dimension 20) generated after passing the test images through the encoder network, and performs principal component analysis (PCA) on the matrix containing the encodings for each of the images. You can then visualize the latent space defined by the means and the variances in the two dimensions characterized by the two first principal components.

The `Generate` function initializes new encodings sampled from a normal distribution, and outputs the images generated when these encodings pass through the decoder network.

`visualizeReconstruction(XTest, YTest, encoderNet, decoderNet)`

`visualizeLatentSpace(XTest, YTest, encoderNet)`

`generate(decoderNet, latentDim)`

### Next Steps

Variational autoencoders are only one of the many available models used to perform generative tasks. They work well on data sets where the images are small and have clearly defined features (such as MNIST). For more complex data sets with larger images, generative adversarial networks (GANs) tend to perform better and generate images with less noise. For an example showing how to implement GANs to generate 64-by-64 RGB images, see Train Generative Adversarial Network (GAN).

### References

1. LeCun, Y., C. Cortes, and C. J. C. Burges. "The MNIST Database of Handwritten Digits." http://yann.lecun.com/exdb/mnist/.

### Helper Functions

#### Model Gradients Function

The `modelGradients` function takes the encoder and decoder `dlnetwork` objects and a mini-batch of input data `X`, and returns the gradients of the loss with respect to the learnable parameters in the networks. The function performs three operations:

1. Obtain the encodings by calling the `sampling `function on the mini-batch of images that passes through the encoder network.

2. Obtain the loss by passing the encodings through the decoder network and calling the `ELBOloss `function.

3. Compute the gradients of the loss with respect to the learnable parameters of both networks by calling the `dlgradient` function.

```function [infGrad, genGrad] = modelGradients(encoderNet, decoderNet, x) [z, zMean, zLogvar] = sampling(encoderNet, x); xPred = sigmoid(forward(decoderNet, z)); loss = ELBOloss(x, xPred, zMean, zLogvar); [genGrad, infGrad] = dlgradient(loss, decoderNet.Learnables, ... encoderNet.Learnables); end```

#### Sampling and Loss Functions

The `sampling` function obtains encodings from input images. Initially, it passes a mini-batch of images through the encoder network and splits the output of size `(2*latentDim)*miniBatchSize` into a matrix of means and a matrix of variances, each of size `latentDim*batchSize`. Then, it uses these matrices to implement the reparameterization trick and to compute the encoding. Finally, it converts this encoding to a `dlarray` object in SSCB format.

```function [zSampled, zMean, zLogvar] = sampling(encoderNet, x) compressed = forward(encoderNet, x); d = size(compressed,1)/2; zMean = compressed(1:d,:); zLogvar = compressed(1+d:end,:); sz = size(zMean); epsilon = randn(sz); sigma = exp(.5 * zLogvar); z = epsilon .* sigma + zMean; z = reshape(z, [1,1,sz]); zSampled = dlarray(z, 'SSCB'); end```

The `ELBOloss` function takes the encodings of the means and the variances returned by the `sampling `function, and uses them to compute the ELBO loss.

```function elbo = ELBOloss(x, xPred, zMean, zLogvar) squares = 0.5*(xPred-x).^2; reconstructionLoss = sum(squares, [1,2,3]); KL = -.5 * sum(1 + zLogvar - zMean.^2 - exp(zLogvar), 1); elbo = mean(reconstructionLoss + KL); end```

#### Visualization Functions

The `VisualizeReconstruction` function randomly chooses two images for each digit of the MNIST data set, passes them through the VAE, and plots the reconstruction side by side with the original input. Note that to plot the information contained inside a `dlarray `object, you need to extract it first using the `extractdata` and `gather` functions.

```function visualizeReconstruction(XTest,YTest, encoderNet, decoderNet) f = figure; figure(f) title("Example ground truth image vs. reconstructed image") for i = 1:2 for c=0:9 idx = iRandomIdxOfClass(YTest,c); X = XTest(:,:,:,idx); [z, ~, ~] = sampling(encoderNet, X); XPred = sigmoid(forward(decoderNet, z)); X = gather(extractdata(X)); XPred = gather(extractdata(XPred)); comparison = [X, ones(size(X,1),1), XPred]; subplot(4,5,(i-1)*10+c+1), imshow(comparison,[]), end end end function idx = iRandomIdxOfClass(T,c) idx = T == categorical(c); idx = find(idx); idx = idx(randi(numel(idx),1)); end```

The `VisualizeLatentSpace` function visualizes the latent space defined by the mean and the variance matrices that form the output of the encoder network, and locates the clusters formed by the latent space representations of each digit.

The function starts by extracting the mean and the variance matrices from the `dlarray` objects. Because transposing a matrix with channel/batch dimensions (C and B) is not possible, the function calls `stripdims` before transposing the matrices. Then, it carries out a principal component analysis (PCA) on both matrices. To visualize the latent space in two dimensions, the function keeps the first two principal components and plots them against each other. Finally, the function colors the digit classes so that you can observe clusters.

```function visualizeLatentSpace(XTest, YTest, encoderNet) [~, zMean, zLogvar] = sampling(encoderNet, XTest); zMean = stripdims(zMean)'; zMean = gather(extractdata(zMean)); zLogvar = stripdims(zLogvar)'; zLogvar = gather(extractdata(zLogvar)); [~,scoreMean] = pca(zMean); [~,scoreLogvar] = pca(zLogvar); c = parula(10); f1 = figure; figure(f1) title("Latent space") ah = subplot(1,2,1); scatter(scoreMean(:,2),scoreMean(:,1),[],c(double(YTest),:)); ah.YDir = 'reverse'; axis equal xlabel("Z_m_u(2)") ylabel("Z_m_u(1)") cb = colorbar; cb.Ticks = 0:(1/9):1; cb.TickLabels = string(0:9); ah = subplot(1,2,2); scatter(scoreLogvar(:,2),scoreLogvar(:,1),[],c(double(YTest),:)); ah.YDir = 'reverse'; xlabel("Z_v_a_r(2)") ylabel("Z_v_a_r(1)") cb = colorbar; cb.Ticks = 0:(1/9):1; cb.TickLabels = string(0:9); axis equal end```

The `generate` function tests the generative capabilities of the VAE. It initializes a `dlarray` object containing 25 randomly generated encodings, passes them through the decoder network, and plots the outputs.

```function generate(decoderNet, latentDim) randomNoise = dlarray(randn(1,1,latentDim,25),'SSCB'); generatedImage = sigmoid(predict(decoderNet, randomNoise)); generatedImage = extractdata(generatedImage); f3 = figure; figure(f3) imshow(imtile(generatedImage, "ThumbnailSize", [100,100])) title("Generated samples of digits") drawnow end```

Download ebook


text:
# What is the solution set for 2x^2 + 4x +10 = 0?

Aug 26, 2015

There are no Real solutions for the given equation.

#### Explanation:

We can see that there are no Real solutions by checking the discriminant
$\textcolor{w h i t e}{\text{XXX}} {b}^{2} - 4 a c$

#color(white)("XXX")= 16 - 80 < 0 color(white)("XX")rarrcolor(white)("XX")no Real roots

or
If we look at the graph for the expression, we can see that it does not cross the X-axis and therefore is not equal to zero at any values for $x$:
graph{2x^2+4x+10 [-10, 10, -5, 5]}

Aug 26, 2015

${x}_{1 , 2} = \frac{- 1 \pm 4 i}{2}$

#### Explanation:

For a general form quadratic equation

$\textcolor{b l u e}{a {x}^{2} + b x + c = 0}$

you can determine its roots by using the quadratic formula

$\textcolor{b l u e}{{x}_{1 , 2} = \frac{- b \pm \sqrt{{b}^{2} - 4 a c}}{2 a}}$

Now, you can divide all the terms by $2$ to make the calculations easier

$\frac{\textcolor{red}{\cancel{\textcolor{b l a c k}{2}}} {x}^{2}}{\textcolor{red}{\cancel{\textcolor{b l a c k}{2}}}} + \left(\frac{4}{2}\right) x + \frac{10}{2} = 0$

${x}^{2} + 2 x + 5 = 0$

For this quadratic, you have $a = 1$, $b = 2$, and $c = 5$, which means that the two roots will be

${x}_{1 , 2} = \frac{- 1 \pm \sqrt{{2}^{2} - 4 \cdot 1 \cdot 5}}{2 \cdot 1}$

Notice that the determinant, $\Delta$, which is the name given to the expression that's under the square root, , is negative.

$\Delta = {b}^{2} - 4 a c$

$\Delta = {2}^{2} - 4 \cdot 1 \cdot 5 = - 16$

For real numbers, you cannot take the square root of a negative number, which means that the quadratic equation has no real solutions.

Its graph will not intercept the $x$-axis. However, it will have two distinct complex roots.

${x}_{1 , 2} = \frac{- 1 \pm \sqrt{- 16}}{2}$

${x}_{1 , 2} = \frac{- 1 \pm \left({i}^{2} \cdot 16\right)}{2} = \frac{- 1 \pm i \cdot \sqrt{16}}{2}$

${x}_{1 , 2} = \frac{- 1 \pm 4 i}{2}$

The two roots will thus be

${x}_{1} = \frac{- 1 + 4 i}{2} \text{ }$ and $\text{ } {x}_{2} = \frac{- 1 - 4 i}{2}$

format: plain


text:
# How do you graph y= (1/2)x by plotting points?

Apr 30, 2017

See explanation

#### Explanation:

I would suggest you chose different values to those I have.

Set $x = 10$ thus $y = \frac{1}{2} \times 10 = 5$

Giving point 1 $\to {P}_{1} \to \left(x , y\right) = \left(10 , 5\right)$

Mark this point on the graph paper

...................................................................................
Set $x = - 10$ thus $y = \frac{1}{2} \times \left(- 10\right) = - 5$

Giving point 2 $\to {P}_{2} \to \left(x , y\right) = \left(- 10 , - 5\right)$

Mark this point on the graph paper
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Using a rule draw a line through these two points. Extend the line to the edges of the graph paper area.


text:
# How can a system of Atwood machine lose gravitational potential energy?

The heavier block in an Atwood machine has a mass twice that of the lighter one. The tension in the string is 16.0 N when the system is set into motion. Find the decrease in the gravitational potential energy during the first second after the system is released from rest.

I don't understand what the question is asking. Whose Gravitational potential energy is mentioned- 1st block or 2nd block?

When lighter block goes up it's gravitational Potential energy increases while that of heavier one decreases(since string is inextensible. So both will move same heights in same time.) so how can the system lose its Gravitational Potential energy?

• The decrease in GPE of the heavier block is larger than the increase of GPE of the lighter block, because it is heavier. So the total GPE of the two goes down. – knzhou Mar 14 at 17:21
• I would suggest just calculating the total potential energy (sum of potential energy of both objects) at the initial point and at some later time point. You will clearly see that the total potential energy decreases – Aaron Stevens Mar 14 at 17:41
• Yes I got that. The masses are unequal. How can I miss that!!!!!!!!!!!!!!!!!!!!!!!!😢 – Hritwik Raj Mar 15 at 18:10

That is simple , take the surface of Earth as your reference frame , the string being inextensible is pulled from both sides by unequal forces (the loads have different masses). Now $$\Delta U=mg\Delta H$$ ,the terms involved have their usual meanings.Its evident that the change with be unequal due to the two unequal masses ,Done ! , the system thus loses Potential energy.
Yet another way to view this is , the conservative force , the gravitational force is doing positive work here , so the potential energy has to reduce , $$\Delta U=-W_{conservative}$$
In a problem like this, the gravitational potential energy of the system can change (and usually does) when the positions of the masses change relative to each other. As block-1 moves downward, the GPE of the block-1/Earth interaction decreases; as block-2 moves up, the GPE of the block2/Earth increases. The block-1/block-2 interaction also contributes to the GPE, but it is negligible by a factor of $$10^{-12}$$ or so. Sum the changes for each pair and that's the total change.


text:
# Show that if $p(x)=a+bx+cx^2$ is a 2nd degree polynomial such that $p(1)=p(2)=p(3)=0$ then $p(x)=0$, using determinants.

Show that if $p(x)=a+bx+cx^2$ is a 2rd degree polynomial such that $p(1)=p(2)=p(3)=0$ then $p(x)=0$ (i.e. $a=b=c=0$), using the determinant of the matrix: $\left(\begin{array}{l}1&x&x^2\\1&y&y^2\\1&z&z^2\end{array}\right)$

Hey everyone. So I managed to prove that the determinant of the given matrix is $(y-x)(z-x)(z-y)$ and therefore the matrix is invertible whenever $x\neq z \lor y\neq x \lor z\neq y$

I've proved this claim using basic algebra but am confused on how to show it using the determinant. I tried showing it by plugging in the values of the polynomial by order:

$\left|\begin{array}{l}a&b&c\\a&2b&4c\\a&3b&9c\end{array}\right|$ (Column operations) $=\left|\begin{array}{l}a&b&c+b+a\\a&2b&4c+2b+a\\a&3b&9c+3b+a\end{array}\right|$ $(p(1)=p(2)=p(3)=0)$$= \left|\begin{array}{l}a&b&0\\a&2b&0\\a&3b&0\end{array}\right|=0$ but this does not help me. I would love to get some help on this question. Thanks in advance.

• Yes: $(1-2)(2-3)(3-1)\neq0,$ which gives $a=b=c=0.$ Feb 24 '18 at 9:56
• It's really a pity to use determinants on this one. I would simply say that $(x-1)(x-2)(x-3)$ is a factor of $p(x)$, end of story. Feb 24 '18 at 9:56
• It is of course a 2nd degree polynomial to begin with ... Feb 24 '18 at 9:58
• @MichaelRozenberg Thank you! I guess I was too confused to see that :)
– Noy
Feb 24 '18 at 9:58

Note that\begin{align}p(1)=p(2)=p(3)=0&\iff\left\{\begin{array}{l}a+b\times1+c\times1^2=0\\a+b\times2+c\times2^2=0\\a+b\times3+c\times3^2=0\end{array}\right.\\&\iff\begin{pmatrix}1&1&1\\1&2&2^2\\1&3&3^2\end{pmatrix}.\begin{pmatrix}a\\b\\c\end{pmatrix}=0.\end{align}So, if $(a,b,c)\neq(0,0,0)$, the determinant of that matrix will be $0$. But it isn't.


text:
# [NTG-context] Convertnumber with \ref[number] fails in MkIV, works in LMTX

Rik Kabel rik at panix.com
Wed Jan 19 18:39:14 CET 2022

This is still a problem with the current standalone.

\definelabel[X][text=]
\startTEXpage[offset=1cm]
\X\X[a]\X[b]\X\par
\convertnumber{R}{\ref[number][a]}
\convertnumber{G}{\ref[number][b]}
\stopTEXpage

%% The above example fails to compile when there is no tuc file,
%%    complaining of a missing number in line 4. When lines 4
%%    and 5 are removed and the file is compiled, producing
%%    a .tuc file, and then they are restored, the example
%%    compiles without error. The effect of having or not having
%%    an associated .tuc file does seem a bit odd.

Surely there is a way to get the number from a label reference that can
then be converted to a numeral of choice.

--
Rik
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.ntg.nl/pipermail/ntg-context/attachments/20220119/2d42ea48/attachment.htm>


text:
# Which font is it? [duplicate]

Possible Duplicate:
How do I find out what fonts are used in a document/picture?

I would know which font it is. Someone could tell me?

-

## marked as duplicate by Matthew Leingang, Guido, Werner, Qrrbrbirlbel, doncherryDec 12 '12 at 5:12

This is the the regular \ttfamily (from Computer Modern) font. –  Werner Dec 12 '12 at 2:17
to use it in that form, what package I should use? –  Mazzy Dec 12 '12 at 2:18
For just the font, use \texttt{...}, or the switch {\ttfamily ...}. For the colour formatting, you'll have to look into the listings package. As it stands, this is a duplicate of How do I find out what fonts are used in a document/picture? –  Werner Dec 12 '12 at 2:19
Just look at the documentation of TikZ/PGF package. You can search your own texmf tree for the doc files it uses a custom listings-like structure. –  percusse Dec 12 '12 at 4:14

As Werner has mentioned, you can use the listings package to produce a similar output; a little example (refer to the package documentation to learn all the customization possibilities it offers):

\documentclass{article}
\usepackage{pgfplots}
\usepackage{listings}
\usepackage{xcolor}

\definecolor{myblue}{RGB}{63,88,167}
\definecolor{mygray}{RGB}{204,202,229}

\lstset{  language=[LaTeX]TeX,
basicstyle=\ttfamily,
keywordstyle=\color{myblue},
backgroundcolor=\color{mygray},
texcsstyle=*\color{black}
}

\begin{document}

\begin{lstlisting}
\begin{tikzpicture}
\begin{axis}[grid=major,width=6cm]


text:
# Calendar

Aug
11
Tue
Jun Le Goh (University of Wisconsin)
Aug 11 @ 4:00 am – 5:00 am

Title: Computing descending sequences in linear orderings
by Jun Le Goh (University of Wisconsin) as part of Computability theory and applications

Abstract
Let DS be the problem of computing a descending sequence in a given ill-founded linear ordering. We investigate the uniform computational content of DS from the point of view of Weihrauch reducibility, in particular its relationship with the analogous problem of computing a path in a given ill-founded tree (known as choice on Baire space).

First, we show that DS is strictly Weihrauch reducible to choice on Baire space. Our techniques characterize the problems which have codomain N and are Weihrauch reducible to DS, thereby identifying the so-called first-order part of DS.

Second, we use the technique of inseparable $Pi^1_1$ sets (first used by Angles d’Auriac, Kihara in this context) to study the strengthening of DS whose inputs are $Sigma^1_1$-codes for ill-founded linear orderings. We prove that this strengthening is still strictly Weihrauch reducible to choice on Baire space.

This is joint work with Arno Pauly and Manlio Valenti.

Helge Glöckner (Universität Paderborn) @ Lecture held in Elysium
Aug 11 @ 6:00 am – 8:00 am

Title: Locally Compact Contraction Groups
by Helge Glöckner (Universität Paderborn) as part of Topological Groups

Lecture held in Elysium.

Abstract
Consider a locally compact group $G$, together with an automorphism $alpha$ which is $contractive$ in the sense that $alpha^nrightarrow{rm id}_G$ pointwise as $ntoinfty$. Siebert showed that $G$ is the direct product of its connected component $G_e$ and an $alpha$-stable, totally disconnected closed subgroup;
moreover, $G_e$ is a simply connected, nilpotent real Lie group.
I’ll report on research concerning the totally disconnected part, obtained jointly with G. A. Willis.

For each totally disconnected contraction group $(G,alpha)$, the set ${rm tor} G$ of torsion elements is a closed subgroup of $G$. Moreover, $G$ is a direct product
$$G=G_{p_1}times cdotstimes G_{p_n}times {rm tor} G$$ of $alpha$-stable $p$-adic Lie groups $G_p$ for certain primes $p_1,ldots, p_n$ and the torsion subgroup. The structure of $p$-adic contraction groups is known from the work of J. S. P. Wang; notably, they are nilpotent. As shown with Willis, ${rm tor} G$ admits a composition series and there are countably many possible composition factors, parametrized by the finite simple groups. More recent research showed that there are uncountably many non-isomorphic torsion contraction groups, but only countably many abelian ones. If a torsion contraction group $G$ has a compact open subgroup which is a pro-$p$-group, then $G$ is nilpotent. Likewise if $G$ is locally pro-nilpotent.

Yulia Kravchenko specialty exam
Aug 11 @ 2:00 pm – 3:00 pm
Aug
18
Tue
Aug 18 @ 6:00 am – 8:00 am

Title: Group dualities: G-barrelled groups

Lecture held in Elysium.

Abstract
A natural notion in the framework of abelian groups are the group dualities. The most efficient definition of a group duality is simply a pair $(G, H)$, where $G$ denotes an abstract abelian group and $H$ a subgroup of characters of $G$, that is $H leq {rm Hom}(G, mathbb T)$. Two group topologies for $G$ and $H$ appear from scratch in a group duality $(G, H)$: the weak topologies $sigma(G, H)$ and $sigma (H, G)$ respectively. Are there more group topologies either in $G$ or $H$ that can be strictly related with the duality $(G, H)$? In this sense we shall define the term “compatible topology” and loosely speaking we consider the compatible topologies as members of the duality.

The locally quasi-convex topologies defined by Vilenkin in the 50′s form a significant class for the construction of a duality theory for groups. The fact that a locally convex topological vector space is in particular a locally quasi-convex group serves as a nexus to emulate well-known results of Functional Analysis for the class of topological groups.

In this talk we shall
deal with questions of the sort:
Under which conditions is there a locally compact topology in a fixed duality?
The same question for a metrizable, or a $k$-group topology.
We shall also introduce the $g$-barrelled groups, a class for which the Mackey-Arens Theorem admits an optimal counterpart. We study also the existence of $g$-barrelled topologies in a group duality $(G, H)$.

Joe Miller (University of Wisconsin)
Aug 18 @ 10:00 am – 11:00 am

Title: Redundancy of information: lowering effective dimension
by Joe Miller (University of Wisconsin) as part of Computability theory and applications

Abstract
A natural way to measure the similarity between two infinite
binary sequences X and Y is to take the (upper) density of their
symmetric difference. This is the Besicovitch distance on Cantor
space. If d(X,Y) = 0, then we say that X and Y are coarsely
equivalent. Greenberg, M., Shen, and Westrick (2018) proved that a
binary sequence has effective (Hausdorff) dimension 1 if and only if
it is coarsely equivalent to a Martin-Löf random sequence. They went
on to determine the best and worst cases for the distance from a
dimension t sequence to the nearest dimension s>t sequence. Thus, the
difficulty of increasing dimension is understood.

Greenberg, et al. also determined the distance from a dimension 1
sequence to the nearest dimension t sequence. But they left open the
general problem of reducing dimension, which is made difficult by the
fact that the information in a dimension s sequence can be coded (at
least somewhat) redundantly. Goh, M., Soskova, and Westrick recently
gave a complete solution.

I will talk about both the results in the 2018 paper and the more
recent work. In particular, I will discuss some of the coding theory
behind these results. No previous knowledge of coding theory is
assumed.

Aug
24
Mon
Fall semester instruction begins
Aug 24 all-day
Aug
25
Tue
Wayne Lewis (University of Hawaiʻi) @ Lecture held in Elysium
Aug 25 @ 6:00 am – 8:00 am

Title: Classification of Periodic LCA Groups of Finite Non-Archimedean Dimension
by Wayne Lewis (University of Hawaiʻi) as part of Topological Groups

Lecture held in Elysium.

Abstract
A periodic LCA group such that the $p$-components all have $p$-rank bounded above by a common positive integer are classified via a complete set of topological isomorphism invariants realized by an equivalence relation on pairs of extended supernatural vectors.

Remaining time will be devoted to a facilitated discussion on how things are going this fall/winter academic semester in your part of the world as you see it.

Andre Nies (University of Auckland)
Aug 25 @ 3:00 pm – 4:00 pm

Title: Discovering structure within the class of K-trivial sets
by Andre Nies (University of Auckland) as part of Computability theory and applications

Abstract
Joint work with Noam Greenberg, Joseph Miller, and Dan Turetsky

The K-trivial sets are antirandom in the sense that the initial segment complexity in terms of prefix-free Kolmogorov complexity K grows as slowly as possible. Chaitin introduced this notion in about 1975, and showed that each K-trivial is Turing below the halting set. Shortly after, Solovay proved that a K-trivial set can be noncomputable.

In the past two decades, many alternative characterisations of this class have been found: properties such as  being low for K, low for Martin-Löf (ML) randomness, and a basis for  ML randomness, which state in one way or the other that the set is close to computable.

Initially, the class of noncomputable K-trivials appeared to be amorphous. More recently, evidence of an internal structure has been found. Most of these results can be phrased in the language of a mysterious reducibility on the K-trivials which is weaker than Turing’s: A is ML-below B if each ML-random computing B also computes A.

Bienvenu, Greenberg, Kucera, Nies and Turetsky (JEMS 2016) showed that there an ML complete K-trivial set. Greenberg, Miller and Nies  (JML, 2019) established a dense hierarchy of subclasses of the K-trivials based on fragments of Omega computing the set, and each such subclass is an initial segment for ML. More recent results generalise these approaches using cost functions. They also show that each K-trivial set is ML-equivalent to a c.e. K-trivial.

The extreme lowness of K-trivials, far from being an obstacle, allows for methods which don’t work in a wider setting. The talk provides an overview and discusses open questions. For instance, is ML-completeness an arithmetical property of K-trivials?


text:
A. Telephone Number
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.

You are given a string $s$ of length $n$, consisting of digits.

In one operation you can delete any character from string $s$. For example, it is possible to obtain strings 112, 111 or 121 from string 1121.

You need to determine whether there is such a sequence of operations (possibly empty), after which the string $s$ becomes a telephone number.

Input

The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases.

The first line of each test case contains one integer $n$ ($1 \le n \le 100$) — the length of string $s$.

The second line of each test case contains the string $s$ ($|s| = n$) consisting of digits.

Output

For each test print one line.

If there is a sequence of operations, after which $s$ becomes a telephone number, print YES.

Otherwise, print NO.

Example
Input
2
13
7818005553535
11
31415926535

Output
YES
NO

Note

In the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535.


text:
Article

# Absorbing Angles, Steiner Minimal Trees, and Antipodality

(Impact Factor: 1.51). 08/2011; 143(1). DOI: 10.1007/s10957-009-9552-1
Source: arXiv

ABSTRACT

We give a new proof that a star $\{op_i:i=1,...,k\}$ in a normed plane is a
Steiner minimal tree of its vertices $\{o,p_1,...,p_k\}$ if and only if all
angles formed by the edges at o are absorbing [Swanepoel, Networks \textbf{36}
(2000), 104--113]. The proof is more conceptual and simpler than the original
one.
We also find a new sufficient condition for higher-dimensional normed spaces
to share this characterization. In particular, a star $\{op_i: i=1,...,k\}$ in
any CL-space is a Steiner minimal tree of its vertices $\{o,p_1,...,p_k\}$ if
and only if all angles are absorbing, which in turn holds if and only if all
distances between the normalizations $\frac{1}{\|p_i\|}p_i$ equal 2. CL-spaces
include the mixed $\ell_1$ and $\ell_\infty$ sum of finitely many copies of
$R^1$.


text:
# How can semi-permeable membrane be so smart?

According to the definition, a semi-permeable membrane is a membrane that allows only solvent molecules to pass through it; solute molecules are blocked. Solvent molecules flow from the membrane side that has low solute concentration (i.e. high solvent concentration) to high solute concentration (i.e. low solvent concentration).

Lets take a case:

1. I take oil as a solvent in one side and water as a solvent in other side. I take the same solute in both sides.
2. Initially, the water side is filled to height $h$ and the oil side to height $2h$. The amount of solute is same in both the sides. So the solute concentration is more in water than in the oil. Accordingly, oil will flow from the oil side to water side. Now, I add more water on the water side to reduce the solute concentration on the oil side. Accordingly, water should now flow towards the oil side.

So what will happen? Will this happen? What makes the semi-permeable membrane so smart or intelligent?

• Water and oil? Do you understand how solubilities work? – Mithoron Feb 13 '16 at 15:38
• @Mithoron I know water and oil are immiscible.. If that was what you meant... I was just trying to give an example .. Please correct or edit my question if you can to explain it better :) – brainst Feb 13 '16 at 17:16

Most of the time what you say about semi-permeable membranes is correct.

a semi-permeable membrane is a membrane that allows only solvent molecules to pass between the membrane; solute molecules are blocked. Solvent molecules flow from the membrane side that has from low solute concentration (i.e. high solvent concentration) to high solute concentration (i.e. low solvent concentration).

However, you have to keep in mind several assumptions that are inherent in the definition as you have given it. The most important of these is that thermodynamic activity differences in the membrane-permeable solvents determine the membrane behavior. When phases are immiscible, such as the water/oil system in your example, it is essential to think in terms of activities, not in terms of concentration.

I take oil as a solvent in one side and water as a solvent in other side. I take the same solute in both sides.

So we are imagining a solute that can be dissolved by both water and by oil. What do we know about the solubility of the solute in these two solvents? What is the partition coefficient? And what can we say about the thermodynamic activity difference across the membrane for the three species? Let's go step by step:

1. Water. Water is not soluble in oil to an appreciable degree. In equilibrated phases, the thermodynamic activity of each chemical species is the same in each phase. Therefore in an oil-water mixture, the thermodynamic activity of water in the aqueous phase is the same as the thermodynamic activity of water in the oil phase. The extremely low solubility of water in oil means that if there were to be a difference in thermodynamic activities across the membrane, only a few molecules would need to cross over for the condition of equal water activities to be satisfied.

2. Oil. Oil is not soluble in water to any appreciable agree. Therefore the same argument applies.

3. Solute. The solute could have a different concentration on each side of the membrane, but because we don't know the partition coefficient, we don't know what the equilibrium state is. Suppose the solute were membrane permeable. Even if it was twice as concentrated in water than in oil, if it's partition coefficient favored an equilibrium where the oil-to-water concentration ratio was 10, then it would flow from the water to the oil. But, in your example the solute is not permeable to the membrane.

Initially, the water side is filled to height $h$ and the oil side to height $2h$. The amount of solute is same in both the sides. So the solute concentration is more in water than in the oil.

Now hopefully the discussion above makes you realize that there aren't many chemiosmotic forces in your example. The only driving force left is hydrostatic pressure. So the oil will cross the membrane, not the water, just because of hydrostatic pressure differences. This is regardless of the solute concentration.

Now, I add more water on the water side to reduce the solute concentration on the oil side. Accordingly, water should now flow towards the oil side.

Well adding more water raises the height $h$ to some higher height and thus increases the hydrostatic pressure. So the increased pressure forces water back through the membrane.

A semi-permeable membrane is not ‘smart’. If you wish, it is actually rather dumb. All it can do is perform a simple selection of ‘I’m letting you through’ versus ‘I’m not letting you through.’ Most membranes will work along the lines of size, polarisability or both.

Size is easily explained: The membrane’s pores have a certain size and what is larger than that cannot diffuse through. Most classical solvents are rather small molecules — water molecules are very small. So it is easy to conceive a membrane that can let water through but has pores too small for large biomolecules or maybe even ions. Remember that dissolved ions are usually surrounded by a solvation sphere, so their size is substantially larger that it may look.

Polarisability is also a rather simple concept but it requires a certain structure of the membrane. The membrane could, for example, consist of a very hydrophobic surface. In that case, ions would likely not want to go near it. It’s a little bit harder to explain, but it may also allow the solvent molecules to go through while the solutes cannot.

Of course, as I said, the membrane is dumb and cannot distinguish solvent from solute. Say you had one that can let water through but not glycerin; maybe due to glycerin’s size. And say you have a $1~\%$ solution of water in glycerin, so $1~\mathrm{g}$ water in $99~\mathrm{g}$ glycerin. The latter is clearly the solvent. However, the membrane would still only let water pass since it is ‘dumb’.

‘Smart’ and ‘dumb’ are bad words altogether, though, since this all is based on physical properties which have nothing to do with smartness (even though smart is a rather frequent keyword in many scientific papers).

Semi-permeable membranes such as cell membranes use active transport to move things AGAINST a concentration gradient (Or through a membrane that would otherwise be impermeable), using energy to do so. You are right, for many materials, things simply balance out like your example. However, in active transport, only some materials are taken in. Here's an article about active transport: https://en.wikipedia.org/wiki/Active_transport


text:
# Clustering, Spatial Correlations, and Randomization Inference

## Author(s): Barrios, Thomas; Diamond, Rebecca; Imbens, Guido W; Kolesar, Michal

To refer to this page use: http://arks.princeton.edu/ark:/88435/pr12n5p
DC FieldValueLanguage
dc.contributor.authorBarrios, Thomas-
dc.contributor.authorDiamond, Rebecca-
dc.contributor.authorImbens, Guido W-
dc.contributor.authorKolesar, Michal-
dc.date.accessioned2020-04-02T21:03:37Z-
dc.date.available2020-04-02T21:03:37Z-
dc.date.issued2012-05-14en_US
dc.identifier.citationBarrios, Thomas, Diamond, Rebecca, Imbens, Guido W, Kolesár, Michal. (2012). Clustering, Spatial Correlations, and Randomization Inference. Journal of the American Statistical Association, 107 (498), 578 - 591. doi:10.1080/01621459.2012.682524en_US
dc.identifier.issn0162-1459-
dc.identifier.urihttp://arks.princeton.edu/ark:/88435/pr12n5p-
dc.description.abstractIt is a standard practice in regression analyses to allow for clustering in the error covariance matrix if the explanatory variable of interest varies at a more aggregate level (e.g., the state level) than the units of observation (e.g., individuals). Often, however, the structure of the error covariance matrix is more complex, with correlations not vanishing for units in different clusters. Here, we explore the implications of such correlations for the actual and estimated precision of least squares estimators. Our main theoretical result is that with equal-sized clusters, if the covariate of interest is randomly assigned at the cluster level, only accounting for nonzero covariances at the cluster level, and ignoring correlations between clusters as well as differences in within-cluster correlations, leads to valid confidence intervals. However, in the absence of random assignment of the covariates, ignoring general correlation structures may lead to biases in standard errors. We illustrate our findings using the 5% public-use census data. Based on these results, we recommend that researchers, as a matter of routine, explore the extent of spatial correlations in explanatory variables beyond state-level clustering.en_US
dc.format.extent578 - 591en_US
dc.language.isoenen_US
dc.relation.ispartofJournal of the American Statistical Associationen_US
dc.rightsAuthor's manuscripten_US
dc.titleClustering, Spatial Correlations, and Randomization Inferenceen_US
dc.typeJournal Articleen_US
dc.identifier.doidoi:10.1080/01621459.2012.682524-
dc.identifier.eissn1537-274X-
pu.type.symplectichttp://www.symplectic.co.uk/publications/atom-terms/1.0/journal-articleen_US

Files in This Item:
File Description SizeFormat


text:
• Post author:

In this article I’ll briefly explain how you can rotate an object, using Unity, in order for it to “look” at the mouse position.

### TL;DR

Here’s the code snippet which will make the player transform point towards the mouse position. Please read below if you’re interested in how this works.

private void PointToMouse(Transform player)
{
var mouseScreenPos = Input.mousePosition;
var startingScreenPos = mainCamera.WorldToScreenPoint(player.position);
mouseScreenPos.x -= startingScreenPos.x;
mouseScreenPos.y -= startingScreenPos.y;
var angle = Mathf.Atan2(mouseScreenPos.y, mouseScreenPos.x) * Mathf.Rad2Deg;
player.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
}

### Explanation

Let’s start with the definition Math.Atan2 that you can find in the Unity documentation:

Returns the angle in radians whose Tan is y/x.
Return value is the angle between the x-axis and a 2D vector starting at zero and terminating at (x,y).

And that’s why, at line 7, we provide the x and y of the mouse position (multiplying everything by the radians-to-degrees conversion constant). But where does all this come from?

To understand that, we need to dust off some old mathematics memories and make use of some linear equation formulas. And so, given two lines:

$\displaystyle y_1 = m_1x_1 + q_1 \\ y_2 = m_2x_2 + q_2$

and their respective slopes m1 and m2, the angle between them is given by:

$\displaystyle \varphi = \arctan \left|\frac{m_1 + m_2}{1 + (m_1m_2)} \right|$

All right but, how do we go from the formula above to the Unity’s one which basically is:

$\displaystyle \tan (\varphi) = \left|\frac{y_2}{x_2}\right| \Rightarrow \varphi = \arctan \left|\frac{y_2}{x_2} \right|$

Simply by considering the first line as the x-axis, and the second one (the one pointing to the mouse) as passing from zero. That gives us the following:

$\displaystyle y_1 = m_1x_1 = 0 \Rightarrow m_1 = 0 \\ \\ y_2 = m_2x_2 \Rightarrow m_2 = \frac{y_2}{x_2}$

And by replacing slopes with their respective values, we end up with:

$\displaystyle \varphi = \arctan \left|\frac{0 + \frac{y_2}{x_2}}{1 + (0\frac{y_2}{x_2})} \right| \Rightarrow \varphi = \arctan \left|\frac{y_2}{x_2} \right|$

### Applying the simplified formula in Unity

In order to use this simplified version in Unity, we need to apply some tweaks. The easiest way to accomplish this is to move from the world-space (measured in units) to the screen-space (measured in pixels). The screen-space comes very handily in this case because it emulates the “first quadrant” of a “Cartesian plane”, where all the x and y are positive. Find more info here.

In order to work on the screen-space, we fetch the mouse position using Input.mousePosition (line 3), and then we have to transform the player position from world to screen coordinates with mainCamera.WorldToScreenPoint(player.position) (line 4). After that, we just need to translate the points (lines 5/6) in order to have the player in (0,0) (remember that Unity’s formula implies the first line to be the x-axis).

Once done, we should end up in a situation like this, and therefore being able to apply our simple formula to retrieve the correct angle and then apply a rotation to the player’s transform (line 8):

### Wrapping up

Unity is a very well done game engine and it perfectly suits both experts and beginners users by hiding some of the complexity involved in the game development world. But I think that sometimes it is worth to understand what’s really going on behind those very simple methods. Whether it is just for curiosity or professional needs, it should help us improve in what we do.


text:
Skip to main content

# 7.3: Thomas Aquinas

Born to an aristocratic family living in Roccasecca, Italy, Thomas Aquinas joined the Dominican order while studying philosophy and theology at Naples. Later he pursued additional studies in Paris and Köln, where he was exposed to Aristotelean thought by Albert the Great and William of Moerbeke. During the rest of his life, he taught at Paris and Rome, writing millions of words on philosophical and theological issues and earning his reputation among the scholastics as “the angelic doctor.” Aquinas developed in massive detail a synthesis of Christianity and Aristotelian philosophythat became the official doctrine of Roman Catholic theology in 1879. De Ente et Essentia (On Being and Essence) includes a basic statement of Aquinas’s metaphysical position. His literary activity stopped abruptly as the result of a religious experience a few months before his death.

Although he wrote many commentaries on the works of Aristotle and a comprehensiveSumma de Veritate Catholicae Fidei contra Gentiles (Summa Contra Gentiles) (1259-1264), Aquinas’s unfinished Summa Theologica (1265-1273) represents the most complete statement of his philosophical system. The sections of greatest interest for survey courses include his views on the nature of god, including the five ways to prove god’s existence, and his exposition of natural law.

Although matters of such importance should be accepted on the basis of divine revelation alone, Aquinas held, it is at least possible (and perhaps even desirable) in some circumstances to achieve genuine knowledge of them by means of the rigorous application of human reason.As embodied souls (hylomorphic composites), human beings naturally rely on sensory information for their knowledge of the world.

Reading hint: Although the rigidly formal structure of the Summa articles can be rather confusing to a modern reader, the central portion beginning with the words, “I answer that…” is always a direct statement of Aquinas’s own position.

 Recommended Reading:Primary sources: Opera omnia (Rome, 1882- )Thomas Aquinas, Selected Writings, ed. by Ralph McInerny. (Penguin, 1999)Thomas Aquinas, Summa Theologica (Thomas More, 1997)Thomas Aquinas, Selected Philosophical Writings, tr. by Timothy McDermott (Oxford, 1998)Thomas Aquinas, Summa Theologiae: A Concise Translation, ed. by Timothy McDermott (Christian Classics, 1997)An Aquinas Reader, ed. by Mary T. Clark (Fordham, 2000)Thomas Aquinas, On Law, Morality, and Politics, ed. by William P. Baumgarth and Richard J. Regan, S.J. (Hackett, 1988) Secondary sources: Etienne Gilson, The Philosophy of St. Thomas Aquinas (Dorset, 1981)The Cambridge Companion to Aquinas, ed. by Norman Kretzmann and Eleonore Stump (Cambridge, 1993)Ralph McInerny, St. Thomas Aquinas (Notre Dame, 1982)The Christian Philosophy of St. Thomas Aquinas, by Etienne Gilson, tr. by I. T. Shook (Notre Dame, 1994)John Milbank and Catherine Pickstock, Truth in Aquinas (Routledge, 2001)John O’Callaghan, Thomist Realism and the Linguistic Turn: Toward a More Perfect Form of Existence(Notre Dame, 2003)Robert Pasnau, Thomas Aquinas on Human Nature: A Philosophical Study of Summa Theologiae 1a 75-89(Cambridge, 2002)Ralph McInerny, Ethica Thomistica: The Moral Philosophy of Thomas Aquinas (Catholic University of America, 1997) HomeAdditional on-line information about Aquinas includes: Daniel J. Kennedy’s *extremely thorough treatment of Aquinas and treatise on his relation to medieval thought at The Jacques Maritain Center.articles in The Stanford Encyclopedia of Philosophy on: Aquinas by Ralph McInerny.The Condemnation of 1277 by Hans Thijssen.The full article available at Encyclopædia Brittanica Online.The thorough collection of resources at EpistemeLinks.com.An article in The Internet Encyclopedia of Philosophy.Robert Sarkissian’s philosophical summary.
CC licensed content, Shared previously

7.3: Thomas Aquinas is shared under a not declared license and was authored, remixed, and/or curated by LibreTexts.

• Was this article helpful?


text:
# Why is my Bubblesort implementation faster than my Quicksort code? [closed]

Here is my Bubblesort code:

public static List<int> BubbleSort(List<int> _digitList)
{
List<int> digitList = _digitList;
bool didSwap = true;

while (didSwap)
{
didSwap = false;
for (int i = 0; i < digitList.Count - 1; i++)
{
if (digitList[i] > digitList[i + 1])
{
int temp = digitList[i];
digitList[i] = digitList[i + 1];
digitList[i + 1] = temp;

didSwap = true;
}
}
}
return digitList;
}

And here is my Quicksort Method, which is actually an implementation of the pseudocode on Wikipedia:

public static List<int> Quicksort(List<int> array)
{
if (array.Count <= 1)
{
return array; //An array of Zero ot one elements is already sorted
}

int pivot = 0;
List<int> less = new List<int>();
List<int> greater = new List<int>();

for (int i = 1; i < array.Count;i++ )
{
if (array[i] <= array[pivot])
{
}
else
{
}
}

List<int> combined = Quicksort(less);

return combined;

}

So for the List = {211, 16, 42, 166, 192, 2, 13, 81, 6, 1, 5, 115, 17, 67}; I get following Stopwatch values.

Bubblesort:

00:00:00.0002873

Quicksort:

00:00:00.0003831

Does this mean my Quicksort code is poor or did I misunderstand the Stopwatch concept?

## closed as off-topic by RubberDuck, SuperBiasedMan, Vogel612♦, Ethan Bierlein, Mathieu GuindonJan 21 '16 at 15:11

If this question can be reworded to fit the rules in the help center, please edit the question.

• If I were you, I'd write many test cases, with different kind of arrays (sorted, reversed, shuffled, all values different, a single value, etc) of different size (empty, small, huge) and ensure that data are properly sorted. Once you've done this, it will be easier to spot if something is wrong in either the correctness or the performances and understand why things do not work the way is it expected. – Josay Mar 24 '14 at 13:23
• Also: don't run a performance test only once – you are still in the millisecond range. Instead: Try counting the number of iterations during a three-second run for a better benchmark. Notice also that your bubblesort works in-place, whereas the quicksort copies each item multiple times. – amon Mar 24 '14 at 13:37
• The code to set pivot to a reasonble value seem to be missing. – Ian Ringrose Mar 24 '14 at 15:10
• I'm voting to close this question as off-topic because Questions asking for explanations of code behavior is off topic. – RubberDuck Jan 21 '16 at 12:17

It is normal in production quality qsort code to switch to another sorting method (maybe a unrolled bubble sort) when the size of the input is small (often 8 is used). QSort has very high overheads, but scales well, for a small input size the overheads are much more important than the scaling.

If you run your code on an input that is 1000 items long, then I expect that your qsort would be faster than your bubble sort.

Try writing a test problem that increases your input size in steps of 100 and then graph the results with both sorting methods.

The other way to look at it, is to find the largest input that each sort method can sort in say 5 seconds.

Also your qSort could be written to be a lot faster by not creating 3 new Lists, it is also very important to quickly choose a good item to privet on. You do not even set the size of the list when you create them, hence each list will have to be reallocated and copied many times as you add items to it.

You have a qSort that is implemented is an inefficient way compared to a boubleSort that is close to the best implementation for boubleSort.

Yet as you confirmed in your comment the qSort does better when you have over 10000 items, slowing just how much better qSort scales.

• You were right, the scaling became significant after an array size of ca. 10000 though. – チーズパン Mar 24 '14 at 14:56
• @bodycountPP, Also your qSort could be written to be a lot faster by not creating 3 new arrays, it is also very important to quickly choose a good item to privet on. – Ian Ringrose Mar 24 '14 at 15:12


text:
## Book review: The Fragmentation of Being

The Fragmentation of Being
by Kris McDaniel (2017)

McDaniel is a contemporary philosopher versed in his field’s arts of analytical hair-splitting who has taken upon himself to resurrect the scholastic doctrine of the analogy of being.  Substances, properties, events, abstractions, possible beings, and propositions clearly don’t all exist in the same way, but calling their different manners of existence by the same word “existence” is equally clearly no mere equivocation.

Being is only one possible instance of analogy.  In general, suppose we have a case of property X that extends across classes A, B, C.  Under what circumstances does X apply analogously (as opposed to univocally) to A vs B vs C?  McDaniel would say that in this case, there are more fundamentally three properties $X_A$, $X_B$, and $X_C$.  Of course, one could for any X just define $X_A$ to be the property of X AND being an A, but for analogous properties, $X_A$ is supposed to be more primitive, so it is preferable to say $X = X_A$ OR $X_B$ OR $X_C$ is the derived property.  McDaniel sometimes formulates this in terms or restricted quantifiers, which I didn’t think really adds any clarity.  More helpfully, he suggests tests for recognizing metaphysical analogy.  For example, an analogous property or relation may require different numbers of terms to be fully specified (“saturated”).  Thus, for concrete objects–but not abstractions–existence might be relative to spacetime region, and for accidents–but not substances–existence is always inherence in a subject.

One way that McDaniel argues for the legitimacy of an analogy of being, and especially related ideas such as degrees or levels of being, is to show that contemporary philosophers are already implicitly using these ideas when they make claims about something being more fundamental or natural than something else, or about something grounding something else.  Armed with gradations of being, he returns to the question of the reality of persons/selves without requiring an all-or-nothing answer.  McDaniel would like to believe that we exist in the most fundamental sense but admits that the question remains open.

The final chapter, on being and essence, has some interesting discussion of the ontological argument.  Interpreting a being’s essence being identical with its existence (as they are said by various philosophers to be for God or Dasein) with its essence being identical with its way of being, McDaniel finds nothing unintelligible in the possibility, although by thus moving “existence” from the act to something more on the essence side, such an identification suffice for an ontological argument for the thing’s existence.  He also makes some points about the possibility of objects having existence claims in their essence.  Clearly, we should not be able to create necessary beings by tacking on “existing” to objects’ essential descriptions.

McDaniel is more interested in recommending the analogy of being broadly conceived than in any specific version of it, so he presents many versions without endorsing any.  In fact, much of the book consists of thinking through the consequences of various metaphysical options, in the end not clearly endorsing any.  I find this a lot in contemporary philosophers.  On the one hand, there is something admirably humble about not pretending to say the last word on any topic.  On the other hand, after a while it leaves me frustrated and despairing of anyone ever reaching any conclusions.

## Book review: What makes time special?

What makes time special?
by Craig Callender (2017)

This book was a joy to read.  Its question can be formulated as follows.  All peoples share a conceptualization of time (as distinguished from our direct sensory experience) that Callender calls “manifest time”–of time “flowing” with a special time “now”, etc.  None of these features appear in physics–Aristotelian, Newtonian, relativistic, or quantum–so where does our sense of manifest time come from?  This question is broken down into parts.

1. Since “now” would be a special spacelike hypersurface of spacetime, it is established that the laws of physics do not justify singling out any particular foliation of spacetime.  This might seem obvious, but Callender wants to show that proposals to inject features of manifest time into physics fail in their goal.  One example is causal set theory.  Callender argues against the theory’s own founder–and I found the argument entirely convincing–that the flowing now in causal set theory is a gauge freedom with no physical significance.  Callender actually gives slightly  more credit that I do to arguments from quantum nonlocality.  He does show that there is only an issue here if one adopts the Copenhagen interpretation and insist within it that there must be some some fact of the matter about which of two spacelike observesrs collapses a wavefunction.  I would not be inclined to grant either premiss.  Even if one does and makes of it an argument for Lorentz’s interpretation of relativity as opposed to Einstein’s, Callender makes an important point.  Lorentz’s preferred frame is completely unobservable and so can’t have anything to do with our experience of time.
2. Physics does indeed give a reason to favor foliations of spacetime into spacelike hypersurfaces, a reason of “narrative”:  the world is more intelligible when cut up this way.  From other hypersurfaces (e.g. a plane extending in t, y, and z representing a “moment” of x), one could constrain the rest of spacetime, but only spacelike hypersurfaces provide initial data for a well-posed Cauchy problem:  the data on the initial slice is unconstrained, and the subsequent (and past) evolution is a continuous function of the initial data.  Ultimately, this comes down to the spacetime metric, which I would say expresses the causal structure of spacetime.  Callender mostly agrees, but his empiricism sometimes leads him to formulate things in (what seems to me) odd ways–that what’s real is observable events, which data can be compressed by fundamental laws of physics which happen to be hyperbolic equations with the same characteristic speeds, which makes it handy to speak of a causal structure of spacetime.
3. The explanation of manifest time must therefore be sought in human psychology.  There is a brief discursion into the argument over indexicals which all philosophy of time works address:  that our statements no more prove that there is metaphysically privileged “now” than that there is a privileged “here” or “me”.  I am skeptical of attempts to tease out metaphysics from grammar, but since it keeps coming up, I guess Callender had to address it.  More substantially, Callender argues against the intuitive belief that we have a direct experience of the present.  We are used to similar arguments from empiricists, e.g. “I have no particular experience of myself; therefore selves don’t exist.”  This argument isn’t quite that bad.  Callender has already given independent arguments that the now of manifest time is an illusion, so all he needs to do here is neutralize the counter-argument that we directly experience this putatively non-existent thing.  One might wonder (although the book doesn’t do so explicitly) if “now” is like the self in that, while not directly experienced, it must be posited to explain a perceived unity of experiences.  In fact, what is needed for this is just an experience of simultaneity, which seems to me rather unthreatening from a physicist’s point of view.  Nevertheless, Callender recounts experiments showing a degree of haziness in perceived simultaneity.  Some of it is interesting–I learned that we process sound faster than sight and that it’s possible to recognize that two stimuli are slightly non-simultaneous without being able to say which came first–but I don’t think it’s necessary for the main argument, which doesn’t hinge on how sharp our sense of simultaneity is.  There follows discussions of IGUS and evolutionary pressures to explain our experience of motion and greater concern over future vs. past pains.  In some ways, this is the most important part of the book, because it is here that manifest time is supposed to actually appear, but given my lack of interest in psychology I didn’t give it as much attention as the rest of the book.

Callender concludes with a criticism of what he sees as the philosophy of time’s disengagement from science and retreat into metaphysics.  In some ways, this complements my criticism of neo-Thomism’s retreat into metaphysics, but Callender drives home a point specific to the philosophy of time.  The point of this branch of philosophy is to explain our experience of time, but it is hard to see how metaphysical constructs that leave no trace on physics could be much use to phenomenology.  For example, even if there is an unobservable preferred frame, how could this have anything to do with how we experience time?

## Now THAT’S survival optimization

Laurent Guyenot at The Unz Review writes

The American rabbi Harry Waton had a theory to explain the organic unity, persistence and progress of the Jews. He wrote in his Program for the Jews, published in 1939: “Hebrew religion, in fact, was intensely materialistic and it is precisely this that gave it persistent and effective reality.”

“Jehovah differs from all other gods. All other gods dwell in heaven. For this reason, all other religions are concerned about heaven, and they promise all reward in heaven after death. For this reason, all other religions negate the earth and the material world and are indifferent to the well-being and progress of mankind on this earth. But Jehovah comes down from heaven to dwell on this earth and to embody himself in mankind. For this reason, Judaism concerns itself only about this earth and promises all reward right here on this earth.”

“The Jews that have a deeper understanding of Judaism know that the only immortality there is for the Jew is the immortality in the Jewish people. Each Jew continues to live in the Jewish people, and he will continue to live so long as the Jewish people will live.”

## the suicidal skepticism of counter-reformation Catholicism

From a comment at What’s Wrong with the World, I was led to this fascinating study of 16th and 17th-century French counter-reformation polemics.  This was when Catholics first embraced skepticism of the ability of human reason to interpret texts as a defense against Protestantism, with predictable long-term effects for the faith itself.

A sample follows.  Famous figures like Montaigne, Descartes, and Richard Simon appear in a rather new light.  The arguments of the Catholic skeptics and the objections to them will be familiar to those who follow today’s religious polemics on the internet, at this site and elsewhere.

## Book review: The Mind of God

The Mind of God:  The Scientific Basis for a Rational World

by Paul Davies (1992)

Davies articulates well several positions which I have also long held

• It is the universe’s combination of orderliness and contingency that metaphysics must explain.
• Multiverses and many-world versions of quantum mechanics won’t resolve the contingency issue, because the laws of physics themselves remain clearly contingent.  (To really get around contingency, you need to embrace full modal realism of the sort defended by philosopher David Lewis.  Surprisingly, some scientists, such as Frank Tipler, are willing to do this, making bizarre claims such as that the universe is a simulation and that mathematical consistency gives an ontological argument for everything.  Neither Davies nor I find this line of thought very credible.)
• The idea that the laws of physics can explain how the universe appeared from “nothing” assumes that these laws have some existence that transcends the natural world they describe, a truly perverse assumption.
• The principle of sufficient reason needs to be qualified to accommodate a contingent but orderly universe.  Some things but not others require explanation.

Davies’ own speculations force him most of the way through the classical cosmological argument for a necessary transcendent God, but he cannot fully accept classical theism because he sees strong, probably insurmountable, difficulties explaining how a simple, necessary God could interact with a contingent, complex universe.  (He is fair enough to point out that many other metaphysical positions, including versions of belief in transcendent laws of physics, have analogous interaction problems.)  He tentatively proposes a model, inspired by process theology, in which God establishes necessary probabalistic laws and potentialities but creatures/events decide by chance/”freedom” what is actualized.  I don’t think this will work, since the laws themselves are non-necessary.

There is an interesting attempt to apply ideas from information theory to give some precision to statements that the universe is “complex” but its laws are “simple”.  Since I don’t know anything about information theory, I enjoyed these parts of the book.

The Mind of God is intended for readers with no physics or philosophy background, but missing information is filled in succinctly enough to avoid boring other readers.

## Book review: The Dappled World

The Dappled World:  A Study of the Boundaries of Science
by Nancy Cartwright (1999)

Cartwright proposes that we are led astray by our expectation that the world is united under a small number of laws.  She thinks it more likely that the world is a patchwork of distinct natures, each with its own regularities.  Predictive laws can only be applied when one has a “nomological machine”, meaning (so far as I can tell) an isolated system where all forces take one of the expected forms.  If one takes seriously the Aristotelian claim that the world is governed by natures rather than a fundamental law, arguably this is what one would expect.

Usually, when one imagines laws of physics breaking down, the idea is that they fail in some untested regime, such as very high energy.  Cartwright appears to be more interested in the idea that they would fail for untested functional forms.  For example, one’s dynamical laws may work for a quadratic but not a quartic potential.  It would be hard to rule out such a possibility, but none of the cases considered in the book pose particular difficulty for the “fundamentalist”, as Cartwright calls believers in unified laws.  Take her example of predicting where a thousand dollar bill carried by the wind will land.  Because we don’t know the exact initial conditions of bill or air, we should consider our initial state as a distribution in some vast state space evolving according to a sort of Liouville equation.  Such a calculation would correctly predict that the bill may fall anywhere in a wide area.  (A full calculation of this sort would be unfeasible, but a sense of the range of possible behavior could easily be gotten by numerically evolving the fluid+bill surface equations for, say, a dozen initial states within the range of uncertainty.)  Just because Newtonian mechanics is uninformative in such cases doesn’t make it wrong.  A more central example in the book is the BCS theory of superconductivity.  Cartwright makes a great deal of the the fact that the BCS Hamiltonian operator is a combination of what one might call “stock components”.  I agree that this illustrates well something about how modeling really works in physics, that in practice one does not start with the most general, fundamental action principle and then start approximating or dropping terms to get to one’s desired system.  However, the message is not that quantum mechanics has some problem with more general Hamiltonians, but that the goal is to capture the essence of superconductivity, so inessential and particularizing details have been dropped.  And it’s easy to see why certain components (esp. quadratic potentials) would be expected to appear in many contexts, as Cartwright acknowledges.  None of this is to say that she is wrong, but the fundamentalist position remains viable.  (Making it explicit and putting it into question, though, can only be good.)qw

Cartwright argues that the way scientists go about their business assumes an Aristotelian multitude of natural capacities and does not fit with Hume’s model of laws as a summary of observed regularities.  She points out that charges moving according to, say, the Coulomb electrostatic force never exactly happens.  The electrostatic force rather describes a tendency, a “what would have happened” if other effects had not been present.  The book then gives an intriguing discussion of Goethe’s criticisms of Newton, arguing that the success of Newton’s optical experiments is more consistent with an Aristotelian world of discrete natures than with Goethe’s more holistic world.

The book ends with some speculations on the relation between classical and quantum mechanics.  Cartwright proposes a sort of property dualism for the physical world, in which systems might have both quantum and classical properties, which presumably would have to interact somehow.

## A world of prophets

Any of us could be destroyed by a social media mob.  Someone takes a picture of you that, without context, gives the impression that you’re being mean or negligent.  They post it on twitter or facebook and a day later a hundred thousand people regard you as the quintessence of evil and want you dead.  When I was a kid, “it’s a free country” was still a common expression; now there are Stasi agents with smartphones everywhere.  How the hell did we let this happen to us?

When I was a kid, you could have an organization devoted just to hiking or wine tasting or space exploration.  Now everybody and everything has to have promoting designated victims as its primary goal.

Two types of religious figure:  the prophet and the priest.  The prophet proclaims God’s wrath, the priest God’s forgiveness.  The prophet condemns social order; the priest consecrates it.  The people admire the prophet who hates them just as they despise the priest who pities them.  For men know that they are wicked, that the whole world of men is wicked, and the priest who offers reconciliation so cheaply seems an agent of corruption.

A priest’s job is to mitigate the cruelty of the moral and religious impulses.