text:
## calculating the p-values in a constrained least squares

I have been using Matlab to perform unconstrained least squares (ordinary least squares) and it automatically outputs the coefficients, test statistic and the p-values.

My question is, upon performing constrained least squares (strictly nonnegative coefficients), it only outputs the coefficients, WITHOUT test statistics, p-values.

Is it possible to calculate these values to ensure significance? And why is it not directly available on the software (or any other software for that matter?)

## Why not use the “normal equations” to find simple least squares coefficients?

I saw this list here and couldn’t believe there were so many ways to solve least squares. The “normal equations” on Wikipedia seemed to be a fairly straight forward way:
\$\$
{displaystyle {begin{aligned}{hat {alpha }}&={bar {y}}-{hat {beta }},{bar {x}},\{hat {beta }}&={frac {sum _{i=1}^{n}(x_{i}-{bar {x}})(y_{i}-{bar {y}})}{sum _{i=1}^{n}(x_{i}-{bar {x}})^{2}}}end{aligned}}}
\$\$

So why not just use them? I assumed there must be a computational or precision issue given that in the first link above Mark L. Stone mentions that SVD or QR are popular methods in statistical software and that the normal equations are “TERRIBLE from reliability and numerical accuracy standpoint”. However, in the following code, the normal equations are giving me accuracy to ~12 decimal places when compared to three popular python functions: numpy’s polyfit; scipy’s linregress; and scikit-learn’s LinearRegression.

What’s more interesting is that the normal equation method is the fastest when n = 100000000. Computational times for me are: 2.5s for linregress; 12.9s for polyfit; 4.2s for LinearRegression; and 1.8s for the normal equation.

Code:

``````import numpy as np
from sklearn.linear_model import LinearRegression
from scipy.stats import linregress
import timeit

b0 = 0
b1 = 1
n = 100000000
x = np.linspace(-5, 5, n)
np.random.seed(42)
e = np.random.randn(n)
y = b0 + b1*x + e

# scipy
start = timeit.default_timer()
print(str.format('{0:.30f}', linregress(x, y)[0]))
stop = timeit.default_timer()
print(stop - start)

# numpy
start = timeit.default_timer()
print(str.format('{0:.30f}', np.polyfit(x, y, 1)[0]))
stop = timeit.default_timer()
print(stop - start)

# sklearn
clf = LinearRegression()
start = timeit.default_timer()
clf.fit(x.reshape(-1, 1), y.reshape(-1, 1))
stop = timeit.default_timer()
print(str.format('{0:.30f}', clf.coef_[0, 0]))
print(stop - start)

# normal equation
start = timeit.default_timer()
slope = np.sum((x-x.mean())*(y-y.mean()))/np.sum((x-x.mean())**2)
stop = timeit.default_timer()
print(str.format('{0:.30f}', slope))
print(stop - start)
``````

## Unsolved Mysteries: Magic Square of Squares

This is the first in what will hopefully be a series of Unsolved Mysteries posts.

Note that this puzzle has no known solution, nor any proof that a solution is impossible. We will see how smart the denizens of Puzzling.SE actually are…!

Most people are familiar with the concept of a Magic Square. (If not, follow the link to read up on it.)

There are algorithms available that make it trivial to construct a magic square of almost any size, but by adding a few constraints to the problem, it becomes much more challenging.

Consider the following \$4times4\$ magic square, where every entry is itself a square number, and the rows, columns and diagonals all sum to \$8515\$:

\$\$
begin{array}\
68^2&29^2&41^2&37^2\
17^2&31^2&79^2&32^2\
59^2&28^2&23^2&61^2\
11^2&77^2&8^2&49^2
end{array}
\$\$

Note that
\$68^2 + 29^2 + 41^2 + 37^2 = 17^2 + 31^2 + 79^2 + 32^2\$
but
\$68 + 29 + 41 + 37 ne 17 + 31 + 79 + 32\$

Only the squared values have the properties of a magic square.

Many such \$4times4\$ squares have been constructed, but as of yet, no one has succeeded in constructing a \$3times3\$ magic square with the same property, nor in proving that no such magic square exists.

Your challenge, therefore, is as follows:

A) Build a \$3times3\$ magic square where each of the nine entries in the square is itself a square number.

or

B) Prove that no such square exists.

For the pedantic among us (you know who you are), here are a few additional constraints:

• Each entry in the square must be unique. (A square consisting entirely of \$4\$s is not valid.)
• The definition of “square number” implies this, but I will spell it out here for those who like to quibble: The entries (before squaring) must be integers. Thus a magic square using values \${ sqrt1^2, sqrt2^2, sqrt3^2, sqrt4^2, sqrt5^2, sqrt6^2, sqrt7^2, sqrt8^2, sqrt9^2}\$ is not valid (although, of course, \$sqrt1^2\$, \$sqrt4^2\$, and \$sqrt9^2\$ can be used in a square, being proper square numbers (\$=1^2, 2^2, 3^2\$).
• This also means that using complex numbers, limits, representations of infinity, or any other abstract mathematical concept is not valid. The intent of the question is obvious; please stick to that.

## Variance of normal distributed least squares estimation

I’m using Least Squares Estimation to find the parameter $$a$$ in the formula $$Y = a * X$$ .

If $$Y$$ ~ $$N(a * X, sigma)$$, how can I calculate $$sigma$$?

I think $$sigma$$ is not the same as the variance of parameter $$a$$.
I hope to hear your thoughts.

## Estimate \$sigma\$ from a data given the total frequency and the sum of squares of frequencies.

In a frequency table with classes of equal width,$$N_1$$ is the total frequency and $$N_2$$ is the sum of squares of the frequencies. Assuming the distribution to be approximately normal with mean $$0$$, I’m asked to suggest a quick estimate of the standard deviation $$sigma$$ in terms of $$N_1$$ and $$N_2$$.

My approach: I’ve first deduced the formula involving the sum of the
square of the density of an $$N(mu,sigma)$$ variate (it doesn’t depend
on $$mu$$) :

$$displaystyleint_{-infty}^{infty}[f(x)]^2,mathrm{dx}=dfrac{1}{2sigmasqrt{pi}}tag*{}$$

Now, $$displaystylesum_{i}dfrac{f(x)}{N_1}=1$$. Then
$$displaystylesum_{i}left(dfrac{f(x)}{N_1}right)^2=dfrac{N_2}{N_1^2}.$$

I think $$displaystylesum_{i}left(dfrac{f(x)}{N_1}right)^2cdot h$$
resembles to
$$displaystyleint_{-infty}^{infty}[f(x)]^2,mathrm{dx}=dfrac{1}{2sigmasqrt{pi}}$$ where $$h=$$ class width.

So,
$$hcdotdfrac{N_2}{N_1^2}=dfrac{1}{2sigmasqrt{pi}}impliessigma=dfrac{2hsqrt{pi}N_2}{N_1^2}.$$

its wrong.

## Prove that given any ï¬ve integers, there will be three for which the sum of the squares of those integers…

Basically the question is asking us to prove that given any integers $$x_1,x_2,x_3,x_4,x_5$$ Prove that 3 of the integers from the set above, suppose $$x_a,x_b,x_c$$ satisfy this equation: $$x_a^2 + x_b^2 + x_c^2 = 3k$$ So I know I am suppose to use the pigeon hole principle to prove this. I know that if I have 5 pigeons and 2 holes then 1 hole will have 3 pigeons. But what I am confused about is how do you define the hole? Do I just say that the container has a property such that if 3 integers are in it then those 3 integers squared sum up to a multiple of 3?

## Practical implementation of Least Squares Monte Carlo (tweaks and pittfalls)

The Longstaff-Schwartz LSM approach is nowadays ubiquitous(at least in the academic literature) in pricing path dependant derivatives. Up to now I have mostly worked with lattice methods. My experience in impelemting those has shown that there are often ways to tweak them and also lot of pittfalls along the way.

To those of you who have some experience in working with LSM:

1. Aside from the usual Monte-Carlo-Optimization techniques (e.g. variance reduction, importance sampling etc.) are there any optimizations that are particular to the LSM approach ?
(Perhaps some paper on the choice of the interpolating polynomial) ?

2. What are possible pittfalls when implementing and working with the
model ? When can LSM go really wrong/ in which cases does it fail to price correctly ?

## Lagrange four squares theorem

Lagrange’s four square theorem states that every non-negative integer is a sum of squares of four non-negative integers. Suppose $$X$$ is a subset of non-negative integers with the same property, that is, every non-negative integer is a sum of squares of four elements if $$X$$.

$$bullet$$ Is $$X={0,1,2,ldots}$$?

$$bullet$$ If not what is a minimal set $$X$$ with the given property?

## BitmapFont in libGDX become squares after hiding and showing screen

My android app written on libGDX has a lot of text. I use FreeTypeFontGenerator to create a font:

``````public static BitmapFont setupHandWritingFont() {
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/handwriting.ttf"));
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = 36;
parameter.genMipMaps = true;
parameter.magFilter = Texture.TextureFilter.Linear;
parameter.color = Color.BLACK;
parameter.characters = "Ð°Ð±Ð²Ð³Ð´ÐµÐ¶Ð·Ð¸Ð¹ÐºÐ»Ð¼Ð½Ð¾Ð¿ÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑÑabcdefghijklmnopqrstuvwxyzÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐ Ð¡Ð¢Ð£Ð¤Ð¥Ð¦Ð§Ð¨Ð©ÐªÐ«Ð¬ÐÐ®Ð¯ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789][_!\$%#@|\/?-+=()*&.;:,{}"Â´`'<>";
BitmapFont font = generator.generateFont(parameter);
generator.dispose();
return font;
}
``````

After some actions, which hide the screen for some time (such as showing ad or hiding the application) text transforms into squares. It happens very often, but not every time. Text looks like this:
Wrong displaying of text

Right displaying of text

Did anybody face this problem before? What may I try to do?

## Fast way to obtain SSR (Sum of Squares residuals) from QR in least square model?

I am using a linear regression, yet the only output I need is the Sum of Squared Residuals (SSR), I don’t care about the coefficients. (Context is a non-linear LS, which is linear given an extra parameter, so I am running a grid search of least-squares SSR)

Is there a fast algorithm to extract the SSR only, with the QR (or other) decomposition? In matrix form:

$$SSR = Y’PY = Y'(I – X(X’X)^{-1}X’)Y$$
and with the QR decomposition, $$X = QR$$, one has $$X(X’X)^{-1}X’=QQ’$$, which suggests one does not need to do a matrix inversion at all, though on the other side, one needs to grow a $$n times n$$ matrix…
SO:

1. Is there a fast algorithm to obtain the SSR only, or am I better sticking with usual function, that compute beta, and also the residuals

2. Is there such an implementation in R, (or linpack/fortran, called by R?). I saw `qr.resid()`, but it seems to be slower than the `lm.fit()`, that returns everything? See benchmark below (changes when X is larger though).

Thanks!

``````data(EuStockMarkets)
X <- EuStockMarkets[1:100, 1:3]
Y <- EuStockMarkets[1:100, 4]

library(microbenchmark)
microbenchmark(lm.fit = c(crossprod(lm.fit(X, Y)$$residuals)), .lm.fit = c(crossprod(.lm.fit(X, Y)$$residuals)),
qr_res = c(crossprod(qr.resid(qr(X), Y))),
times = 10)
#> Unit: microseconds
#>     expr    min     lq    mean  median     uq     max neval
#>   lm.fit 44.566 45.704 97.3347 47.0335 51.143 543.285    10
#>  .lm.fit 11.144 11.995 15.0783 13.1285 13.856  35.594    10
#>   qr_res 49.495 51.841 79.9043 53.4505 55.014 317.989    10
``````

Created on 2018-10-20 by the reprex package (v0.2.1)


text:
Home OALib Journal OALib PrePrints Submit Ranking News My Lib FAQ About Us Follow Us+
 Title Keywords Abstract Author All
Search Results: 1 - 10 of 100 matches for " "
 Page 1 /100 Display every page 5 10 20 Item
 Physics , 2013, DOI: 10.1103/PhysRevLett.111.027601 Abstract: By combining x-ray excited Auger electron diffraction experiments and multiple scattering calculations we reveal a layer-resolved shift for the Mg KL23L23 Auger transition in MgO ultrathin films (4-6 \AA) on Ag(001). This resolution is exploited to demonstrate the possibility to control Mg atoms incorporation at the MgO/Ag(001) interface by exposing the MgO films to a Mg flux. A substantial reduction of the MgO/Ag(001) work function is observed during the exposition phase and reflects, both band-offset variations at the interface and band bending effects in the oxide film.
 Physics , 2002, DOI: 10.1103/PhysRevB.68.035429 Abstract: The formation of patterned nanostructure in AgCo/Pt/MgO(001) thin film is simulated by a technique of combining molecular dynamics and phase-field theory. The dislocation (strain) network existing in Pt/MgO is used as a template whose pattern is transferred to AgCo phase in spinodal decomposition, resulting in regular arrays of Co islands that are attracted by the dislocations. The influence of various factors, such as component concentration and film thickness, is studied. It is found that the spinodal decomposition of AgCo in this system is mainly characterized by a competition between a surface-directed layer structure and the strain-induced patterned structure, where the patterned Ag-Co structure only dominates in a small range near the interface (less than 10 atomic layers). However, if the interlayer diffusion can be minimized by controlling film growth conditions, it is shown that the patterned structure can be formed throughout the entire film.
 Physics , 2015, DOI: 10.1063/1.4916296 Abstract: The spin and orbital magnetic moments of the Fe3O4 epitaxial ultrathin film synthesized by plasma assisted simultaneous oxidization on MgO(100) have been studied with X-ray magnetic circular dichroism (XMCD). The ultrathin film retains a rather large total magnetic moment, i.e. (2.7+-0.15) uB/f.u., which is ~ 70% of that for the bulk-like Fe3O4. A significant unquenched orbital moment up to (0.54+-0.05) uB/f.u. was observed, which could come from the symmetry breaking at the Fe3O4/MgO interface. Such sizable orbital moment will add capacities to the Fe3O4-based spintronics devices in the magnetization reversal by the electric field.
 Physics , 2012, DOI: 10.1063/1.4704685 Abstract: We investigate the initial growth modes and the role of interfacial electrostatic interactions of EuO epitaxy on MgO(001) by reactive molecular beam epitaxy. A TiO2 interfacial layer is employed to produce high quality epitaxial growth of EuO on MgO(001) with a 45{\deg} in plane rotation. For comparison, direct deposition of EuO on MgO, without the TiO2 layer shows a much slower time evolution in producing a single crystal film. Conceptual arguments of electrostatic repulsion of like-ions are introduced to explain the increased EuO quality at the interface with the TiO2 layer. It is shown that ultrathin EuO films in the monolayer regime can be produced on the TiO2 surface by substrate-supplied oxidation and that such films have bulk-like magnetic properties.
 Physics , 2015, Abstract: We model the remarkable thin-film Ba-Ti-O structures formed by heat treatment of an initial perovskite BaTiO3 thin film on a Pt(111) surface. All structures contain a rumpled Ti-O network with all Ti threefold coordinated with O, and with Ba occupying the larger. mainly Ti7O7, pores. The quasicrystal structure is a simple decoration of three types of tiles: square, triangle and 30 degree rhombus, with edge lengths 6.85 Angstroms, joined edge-to-edge in a quasicrystalline pattern; observed crystalline Ba-Ti-O structures are built from these and other tiles. Simulated STM images reproduce the patterns seen experimentally, and identify the bright protrusions as Ba atoms. The models are consistent with all experimental observations.
 Physics , 2013, Abstract: We present a detailed ab initio study of the electronic structure and magnetic order of an Fe monolayer on the Ir(001) surface covered by adsorbed oxygen and hydrogen. The results are compared to the clean Fe/Ir(001) system, where recent intensive studies indicated a strong tendency towards an antiferromagnetic order and complex magnetic structures. The adsorption of an oxygen overlayer significantly increases interlayer distance between the Fe layer and the Ir substrate, while the effect of hydrogen is much weaker. We show that the adsorption of oxygen (and also of hydrogen) leads to a p(2$\times$1) antiferromagnetic order of the Fe moments, which is also supported by an investigation based on a disordered local moment state. Simulated scanning tunneling images using the simple Tersoff-Hamann model hint that the proposed p(2$\times$1) antiferromagnetic order could be detected even by non-magnetic tips.
 Physics , 2013, DOI: 10.1063/1.3663574 Abstract: We analyze X-ray diffraction data used to extract cell parameters of ultrathin films on closely matching substrates. We focus on epitaxial La2/3Sr1/3MnO3 films grown on (001) SrTiO3 single crystalline substrates. It will be shown that, due to extremely high structural similarity of film and substrate, data analysis must explicitly consider the distinct phase of the diffracted waves by substrate and films to extract reliable unit cell parameters. The implications of this finding for the understanding of strain effects in ultrathin films and interfaces will be underlined
 Physics , 2015, Abstract: For a ultrathin NiO(001) film of 4 monolayers (ML) thickness grown on Ag(001), the vibrational properties have been determined by high-resolution electron energy loss spectroscopy (HREELS). For the well-ordered pseudomorphically grown film, nine phonon modes have been identified and their dispersions have been revealed along the Gamma-X high-symmetry direction. The comparison with phonon data for a 25 ML thick NiO(001) film shows that the NiO (001) phonon properties are already fully developed at 4 ML. Significant differences are found for the surface-localized phonon S6 which has an increased dispersion for the ultrathin film. The dipole-active Fuchs-Kliewer phonon-polariton exhibits a narrower lineshape than the mode found for a single-crystal surface, which might hint to a reduced antiferromagnetic coupling in the ultrathin film.
 Physics , 2009, DOI: 10.1143/APEX.2.063001 Abstract: Growing demands for the voltage-driven spintronic applications with ultralow-power consumption have led to new interest in exploring the voltage-induced magnetization switching in ferromagnetic metals. In this study, we observed a large perpendicular magnetic anisotropy change in Au(001) / ultrathin Fe80Co20(001) / MgO(001) / Polyimide / ITO junctions, and succeeded in realizing a clear switching of magnetic easy axis between in-plane and perpendicular directions. Furthermore, employing a perpendicularly magnetized film, voltage-induced magnetization switching in the perpendicular direction under the assistance of magnetic fields was demonstrated. These pioneering results may open a new window of electric-field controlled spintronics devices.
 Physics , 2015, Abstract: Crystalline Fe3O4/NiO bilayers were grown on MgO(001) substrates using reactive molecular beam epitaxy to investigate their structural properties and their morphology. The film thickness either of the Fe3O4 film or of the NiO film has been varied to shed light on the relaxation of the bilayer system. The surface properties as studied by x-ray photo electron spectroscopy and low energy electron diffraction show clear evidence of stoichiometric well-ordered film surfaces. Based on the kinematic approach x-ray diffraction experiments were completely analyzed. As a result the NiO films grow pseudomorphic in the investigated thickness range (up to 34nm) while the Fe3O4 films relax continuously up to the thickness of 50nm. Although all diffraction data show well developed Laue fringes pointing to oxide films of very homogeneous thickness, the Fe3O4-NiO interface roughens continuously up to 1nm root-mean-square roughness with increasing NiO film thickness while the Fe3O4 surface is very smooth independent on the Fe3O4 film thickness. Finally, the Fe3O4-NiO interface spacing is similar to the interlayer spacing of the oxide films while the NiO-MgO interface is expanded.
 Page 1 /100 Display every page 5 10 20 Item

format: plain


text:
# Lecture 3

## Introduction

• So far, we’ve discussed how to build simple web pages using HTML and CSS, and how to use Git and GitHub in order to keep track of changes to our code and collaborate with others. We also familiarized ourselves with the Python programming language.
• Today, we’ll work on using Python’s Django framework in order to create dynamic applications.

## Web Applications

So far, all of the web applications we’ve written have been static. This means that every single time we open that web page, it looks exactly the same. Many websites we visit every day, however, change every time we visit them. If you visit the websites of the New York Times or Facebook, for example, you’ll most likely see different things today than you will tomorrow. For large sites like those, it would be unreasonable for employees to have to manually edit a large HTML file every time a change is made, which is where dynamic websites can be extremely useful. A dynamic website is one that takes advantage of a programming language (such as Python) to dynamically generate HTML and CSS files. During this lecture, we’ll learn how to create our first dynamic applications.

## HTTP

HTTP, or HyperText Transfer Protocol, is a widely-accepted protocol for how messages are transfered back and forth across the internet. Typically, information online is passed between a client (user) and a server.

In this protocol, the client will send a request to the server, that might look something like the one below. In the example below, GET is simply a type of request, one of three we’ll discuss in this course. The / typically indicates that we’re looking for the website’s home page, and the three dots indicate that we could be passing in more information as well.

After receiving a request, a server will then send back an HTTP response, which might look something like the one below. Such a response will include the HTTP version, a status code (200 means OK), a description of the content, and then some additional information.

200 is just one of many status codes, some of which you may have seen in the past:

## Django

Django is a Python-based web framework that will allow us to write Python code that dynamically generates HTML and CSS. The advantage to using a framework like Django is that a lot of code is already written for us that we can take advantage of.

• To get started, we’ll have to install Django, which means you’ll also have to install pip if you haven’t already done so.
• Once you have Pip installed, you can run pip3 install Django in your terminal to install Django.

After installing Django, we can go through the steps of creating a new Django project:

1. Run django-admin startproject PROJECT_NAME to create a number of starter files for our project.
2. Run cd PROJECT_NAME to navigate into your new project’s directory.
3. Open the directory in your text editor of choice. You’ll notice that some files have been created for you. We won’t need to look at most of these for now, but there are three that will be very important from the start:
• manage.py is what we use to execute commands on our terminal. We won’t have to edit it, but we’ll use it often.
• settings.py contains some important configuration settings for our new project. There are some default settings, but we may wish to change some of them from time to time.
• urls.py contains directions for where users should be routed after navigating to a certain URL.
4. Start the project by running python manage.py runserver. This will open a development server, which you can access by visiting the URL provided. This development server is being run locally on your machine, meaning other people cannot access your website. This should bring you to a default landing page:
5. Next, we’ll have to create an application. Django projects are split into one or more applications. Most of our projects will only require one application, but larger sites can make use of this ability to split a site into multiple apps. To create an application, we run python manage.py startapp APP_NAME. This will create some additional directories and files that will be useful shortly, including views.py.
6. Now, we have to install our new app. To do this, we go to settings.py, scroll down to the list of INSTALLED_APPS, and add the name of our new application to this list.

## Routes

Now, in order to get started with our application:

1. Next, we’ll navigate to views.py. This file will contain a number of different views, and we can think of a view for now as one page the user might like to see. To create our first view, we’ll write a function that takes in a request. For now, we’ll simply return an HttpResponse (A very simple response that includes a response code of 200 and a string of text that can be displayed in a web browser) of “Hello, World”. In order to do this, we have include from django.http import HttpResponse. Our file now looks like:

 from django.shortcuts import render
from django.http import HttpResponse

def index(request):
return HttpResponse("Hello, world!")

2. Now, we need to somehow associate this view we have just created with a specific URL. To do this, we’ll create another file called urls.py in the same directory as views.py. We already have a urls.py file for the whole project, but it is best to have a separate one for each individual app.
3. Inside our new urls.py, we’ll create a list of url patterns that a user might visit while using our website. In order to do this:
1. We have to make some imports: from django.urls import path will give us the ability to reroute URLSs, and from . import views will import any functions we’ve created in views.py.
2. Create a list called urlpatterns
3. For each desired URL, add an item to the urlpatterns list that contains a call to the path function with two or three arguments: A string representing the URL path, a function from views.py that we wish to call when that URL is visited, and (optionally) a name for that path, in the format name="something". For example, here’s what our simple app looks like now:
 from django.urls import path
from . import views

urlpatterns = [
path("", views.index, name="index")
]

4. Now, we’ve created a urls.py for this specific application, and it’s time to edit the urls.py created for us for the entire project. When you open this file, you should see that there’s already a path called admin which we’ll go over in later lectures. We want to add another path for our new app, so we’ll add an item to the urlpatterns list. This follows the same pattern as our earlier paths, except instead of adding a function from views.py as our second argument, we want to be able to include all of the paths from the urls.py file within our application. To do this, we write: include("APP_NAME.urls"), where include is a function we gain access to by also importing include from django.urls as shown in the urls.py below:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('hello/', include("hello.urls"))
]

5. By doing this, we’ve specified that when a user visits our site, and then in the search bar adds /hello to the URL, they’ll be redirected to the paths inside of our new application.

Now, when I start my application using python manage.py runserver and visit the url provided, I’m met with this screen: But this is because we have only defined the URL localhost:8000/hello, but we haven’t defined the URL localhost:8000 with nothing added to the end. So, when I add /hello to the URL in my search bar: Now that we’ve had some success, let’s go over what just happened to get us to that point:

1. When we accessed the URL localhost:8000/hello/, Django looked at what came after the base URL (localhost:8000/) and went to our project’s urls.py file and searched for a pattern that matched hello.
2. It found that extension because we defined it, and saw that when met with that extension, it should include our urls.py file from within our application.
3. Then, Django ignored the parts of the URL it has already used in rerouting (localhost:8000/hello/, or all of it) and looked inside our other urls.py file for a pattern that matches the remaining part of the URL.
4. It found that our only path so far ("") matched what was left of the URL, and so it directed us to the function from views.py associated with that path.
5. Finally, Django ran that function within views.py, and returned the result (HttpResponse("Hello, world!")) to our web browser.

Now, if we want to, we can change the index function within views.py to return anything we want it to! We could even keep track of variables and do calculations within the function before eventually returning something.

Now, let’s take a look at how we can add more than one view to our application. We can follow many of the same steps within our application to create pages that say hello to Brian and David.

Inside views.py:

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
return HttpResponse("Hello, world!")

def brian(request):
return HttpResponse("Hello, Brian!")

def david(request):
return HttpResponse("Hello, David!")

Inside urls.py (within our application)

from django.urls import path
from . import views

urlpatterns = [
path("", views.index, name="index"),
path("brian", views.brian, name="brian"),
path("david", views.david, name="david")
]

Now, our site remains unchanged when we visit localhost:8000/hello, but we get different pages when we add brian or david to the URL:

Many sites are parameterized by items included in the URL. For example, going to www.twitter.com/cs50 will show you all of CS50’s tweets, and going to www.github.com/cs50 will bring you to CS50’s GitHub page. You can even find your own public GitHub repositories by navigating to www.github.com/YOUR_USERNAME!

In thinking about how this is implemented, it seems impossible that sites like GitHub and Twitter would have an individual URL path for each of its users, so let’s look into how we could make a path that’s a bit more flexible. We’ll start by adding a more general function, called greet, to views.py:

def greet(request, name):
return HttpResponse(f"Hello, {name}!")

This function takes in not only a request, but also an additional argument of a user’s name, and then returns a custom HTTP Response based on that name. Next, we have to create a more flexible path in urls.py, which could look somehting like this:

path("<str:name>", views.greet, name="greet")

This is some new syntax, but essentially what’s going on here is we’re no longer looking for a specific word or name in the URL, but any string that a user might enter. Now, we can try the site out with a few other URLs:

I can even make these look a little bit nicer, by augmenting the greet function to utilize Python’s capitalize function that capitalizes a string:

def greet(request, name):
return HttpResponse(f"Hello, {name.capitalize()}!")

This is a great illustration of how any functionality we have in Python can be used in Django before being returned.

## Templates

So far, our HTTP Responses, have been only text, but we can include any HTML elements we want to! For example, I could decide to return a blue header instead of just the text in our index function:

def index(request):
return HttpResponse("
Hello, world!
")

It would get very tedious to write an entire HTML page within views.py. It would also constitute bad design, as we want to keep separate parts of our project in separate files whenever possible.

This is why we’ll now introduce Django’s templates, which will allow us to write HTML and CSS in separate files and render those files using Django. The syntax we’ll use for rendering a template looks like this:

def index(request):
return render(request, "hello/index.html")

Now, we’ll need to create that template. To do this, we’ll create a folder called templates inside our app, then create a folder called hello (or whatever our app’s name is) within that, and then add a file called index.html.

Next, we’ll add whatever we want to that new file:

<!DOCTYPE html>

<title>Hello</title>

Hello, World!

Now, when we visit the main page of our application, we can see the header and title have been updated:

In addition to writing some static HTML pages, we can also use Django’s templating language to change the content of our HTML files based on the URL visited. Let’s try it out by changing our greet function from earlier:

def greet(request, name):
return render(request, "hello/greet.html", {
"name": name.capitalize()
})

Notice that we passed a third argument into the render function here, one that is known as the context. In this context, we can provide information that we would like to have available within our HTML files. This context takes the form of a Python dictionary. Now, we can create a greet.html file:

<!DOCTYPE html>

<title>Hello</title>

Hello, {{ name }}!

You’ll noticed that we used some new syntax: double curly brackets. This syntax allows us to access variables that we’ve provided in the context argument. Now, when we try it out:

Now, we’ve seen how we can modify our HTML templates based on the context we provide. However, the Django templating language is even more powerful than that, so let’s take a look at a few other ways it can be helpful:

### Conditionals:

We may want to change what is displayed on our website depending on some conditions. For example, if you visit the site www.isitchristmas.com, you’ll probably be met with a page that looks like this: But this website will change on Christmas day, when the website will say YES. To make something like this for ourselves, let’s try creating a similar application, where we check whether or not it is New Year’s Day. Let’s create a new app to do so, recalling our process for creating a new app:

1. run python manage.py startapp newyear in the terminal.
2. Edit settings.py, adding “newyear” as one of our INSTALLED_APPS
3. Edit our project’s urls.py file, and include a path similar to the one we created for the hello app:
path('newyear/', include("newyear.urls"))

1. Create another urls.py file within our new app’s directory, and update it to include a path similar to the index path in hello:
from django.urls import path
from . import views

urlpatterns = [
path("", views.index, name="index"),
]

1. Create an index function in views.py.

Now that we’re set up with our new app, let’s figure out how to check whether or not it’s New Year’s Day. To do this, we can import Python’s datetime module. To get a sense for how this module works, we can look at the documentation, and then test it outside of Django using the Python interpreter.

• The Python interpreter is a tool we can use to test out small chunks of Python code. To use this, run python in your terminal, and then you’ll be able to type and run Python code within your terminal. When you’re done using the interpreter, run exit() to leave.
• We can use this knowledge to construct a boolean expression that will evaluate to True if and only if today is New Year’s Day: now.day == 1 and now.month == 1
• Now that we have an expression we can use to evaluate whether or not it’s New Year’s Day, we can update our index function in views.py:
def index(request):
now = datetime.datetime.now()
return render(request, "newyear/index.html", {
"newyear": now.month == 1 and now.day == 1
})

Now, let’s create our index.html template. We’ll have to again create a new folder called templates, a folder within that called newyear, and a file within that called index.html. Inside that file, we’ll write something like this:

<!DOCTYPE html>

<title>Is it New Year's?</title>

{% if newyear %}

YES

{% else %}

NO

{% endif %}

In the code above, notice that when we wish to include logic in our HTML files, we use {% and %} as opening and closing tags around logical statements. Also note that Django’s formatting language requires you to include an ending tag indicating that we are done with our if-else block. Now, we can open up to our page to see:

Now, to get a better idea of what’s going on behind the scenes, let’s inspect the element of this page:

Notice that the HTML that is actually being sent to your web browser includes only the NO header, meaning that Django is using the HTML template we wrote to create a new HTML file, and then sending it to our web browser. If we cheat a little bit and make sure that our condition is always true, we see that the opposite case is filled:

def index(request):
now = datetime.datetime.now()
return render(request, "newyear/index.html", {
"newyear": True
})

### Styling

If we want to add a CSS file, which is a static file because it doesn’t change, we’ll first create a folder called static, then create a newyear folder within that, and then a styles.css file within that. In this file, we can add any styling we wish just as we did in the first lecture:

h1 {
font-family: sans-serif;
font-size: 90px;
text-align: center;
}

Now, to include this styling in our HTML file, we add the line {% load static %} to the top of our HTML template, which signals to Django that we wish to have access to the files in our static folder. Then, rather than hard-coding the link to a stylesheet as we did before, we’ll use some Django-specific syntax:

<link rel="stylesheet" href="{% static 'newyear/styles.css' %}">

Now, if we restart the server, we can see that the styling changes were in fact applied:

Now, let’s take what we’ve learned so far and apply it to a mini-project: creating a TODO list. Let’s start by, once again, creating a new app:

1. run python manage.py startapp tasks in the terminal.
2. Edit settings.py, adding “tasks” as one of our INSTALLED_APPS
3. Edit our project’s urls.py file, and include a path similar to the one we created for the hello app:

 path('tasks/', include("tasks.urls"))

4. Create another urls.py file within our new app’s directory, and update it to include a path similar to the index path in hello:

 from django.urls import path
from . import views

urlpatterns = [
path("", views.index, name="index"),
]

5. Create an index function in views.py.

Now, let’s begin by attempting to simply create a list of tasks and then display them to a page. Let’s create a Python list at the top of views.py where we’ll store our tasks. Then, we can update our index function to render a template, and provide our newly-created list as context.

from django.shortcuts import render

def index(request):
})

Now, let’s work on creating our template HTML file:

<!DOCTYPE html>

{% endfor %}

Notice here that we are able to loop over our tasks using syntax similar to our conditionals from earlier, and also similar to a Python loop from Lecture 2. When we go to the tasks page now, we can see our list being rendered:

## Forms

Now that we can see all of our current tasks as a list, we may want to be able to add some new tasks. To do this we’ll start taking a look at using forms to update a web page. Let’s begin by adding another function to views.py that will render a page with a form for adding a new task:

# Add a new task:

Next, make sure to add another path to urls.py:

path("add", views.add, name="add")

Now, we’ll create our add.html file, which is fairly similar to index.html, except that in the body we’ll include a form rather than a list:

<!DOCTYPE html>

<form action="">
<input type="submit">
</form>

However, what we’ve just done isn’t necessarily the best design, as we’ve just repeated the bulk of that HTML in two different files. Django’s templating language gives us a way to eliminate this poor design: template inheritance. This allows us to create a layout.html file that will contain the general structure of our page:

<!DOCTYPE html>

{% block body %}
{% endblock %}

Notice that we’ve again used {%...%} to denote some sort of non-HTML logic, and in this case, we’re telling Django to fill this “block” with some text from another file. Now, we can alter our other two HTML files to look like:

index.html:

{% extends "tasks/layout.html" %}

{% block body %}

{% endfor %}

{% endblock %}

add.html:

{% extends "tasks/layout.html" %}

{% block body %}
<form action="">
<input type="submit">
</form>
{% endblock %}

Notice how we can now get rid of much of the repeated code by extending our layout file. Now, our index page remains the same, and we now have an add page as well:

Next, it’s not ideal to have to type “/add” in the URL any time we want to add a new task, so we’ll probably want to add some links between pages. Instead of hard-coding links though, we can now use the name variable we assigned to each path in urls.py, and create a link that looks like this:

Add a New Task

where ‘add’ is the name of that path. We can do a similar thing in our add.html:

View Tasks

This could potentially create a problem though, as we have a few routes named index throughout our different apps. We can solve this by going into each of our app’s urls.py file, and adding an app_name variable, so that the files now look something like this:

from django.urls import path
from . import views

urlpatterns = [
path("", views.index, name="index"),
]

We can then change our links from simply index and add to tasks:index and tasks:add

View Tasks

Now, let’s work on making sure the form actually does something when the user submits it. We can do this by adding an action to the form we have created in add.html:

<form action="{% url 'tasks:add' %}" method="post">

This means that once the form is submitted, we will be routed back to the add URL. Here we’ve specified that we’ll be using a post method rather than a get method, which is typically what we’ll use any time a form could alter the state of that web page.

We need to add a bit more to this form now, because Django requires a token to prevent Cross-Site Request Forgery (CSRF) Attack. This is an attack where a malicious user attempts to send a request to your server from somewhere other than your site. This could be a really big problem for some websites. Say, for example, that a banking website has a form for one user to transfer money to another one. It would be catastrophic if someone could submit a transfer from outside of the bank’s website!

To solve this problem, when Django sends a response rendering a template, it also provides a CSRF token that is unique with each new session on the site. Then, when a request is submitted, Django checks to make sure the CSRF token associated with the request matches one that it has recently provided. Therefore, if a malicious user on another site attempted to submit a request, they would be blocked due to an invalid CSRF token. This CSRF validation is built into the Django Middleware framework, which can intervene in the request-response processing of a Django app. We won’t go into any more detail about Middleware in this course, but do look at the documentation if interested!

To incorporate this technology into our code, we must add a line to our form in add.html.

<form action="{% url 'tasks:add' %}" method="post">
{% csrf_token %}
<input type="submit">
</form>

This line adds a hidden input field with the CSRF token provided by Django, such that when we reload the page, it looks as though nothing has changed. However, if we inspect element, we’ll notice that a new input field has been added:

### Django Forms

While we can create forms by writing raw HTML as we’ve just done, Django provides an even easier way to collect information from a user: Django Forms. In order to use this method, we’ll add the following to the top of views.py to import the forms module:

from django import forms

Now, we can create a new form within views.py by creating a Python class called NewTaskForm:

class NewTaskForm(forms.Form):

Now, let’s go through what’s going on in that class:

• Inside the parentheses after NewTaskForm, we see that we have forms.Form. This is because our new form inherits from a class called Form that is included in the forms module. We’ve already seen how inheritance can be used in Django’s templating language and for styling using Sass. This is another example of how inheritance is used to take a more general description (the forms.Form class) and narrow it down to what we want (our new Form). Inheritance is a key part of Object Oriented Programming that we won’t discuss in detail during this course, but there are many online resources available to learn about the topic!
• Inside this class, we can specify what information we would like to collect from the user, in this case the name of a task.
• We specify that this should be a textual input by writing forms.CharField, but there are many other input fields included in Django’s form module that we can choose from.
• Within this CharField, we specify a label, which will appear to the user when they load the page. A label is just one of many arguments we can pass into a form field.

Now that we’ve created a NewTaskForm class, we can include it in the context while rendering the add page:

# Add a new task:
})

Now, within add.html, we can replace our input field with the form we just created:

{% extends "tasks/layout.html" %}

{% block body %}
{% csrf_token %}
{{ form }}
<input type="submit">
</form>
{% endblock %}

There are several advantages to using the forms module rather than manually writing an HTML form:

• If we want to add new fields to the form, we can simply add them in views.py without typing additional HTML.
• Django automatically performs client-side validation, or validation local to the user’s machine. meaning it will not allow a user to submit their form if it is incomplete.
• Django provides simple server-side validation, or validation that occurs once form data has reached the server.
• In the next lecture, we’ll begin using models to store information, and Django makes it very simple to create a form based on a model.

Now that we have a form set up, let’s work on what happens when a user clicks the submit button. When a user navigates to the add page by clicking a link or typing in the URL, they submit a GET request to the server, which we’ve already handled in our add function. When a user submits a form though, they send a POST request to the server, which at the moment is not handled in the add function. We can handle a POST method by adding a condition based on the request argument our function takes in. The comments in the code below explain the purpose of each line:

# Add a new task:

# Check if method is POST
if request.method == "POST":

# Take in the data the user submitted and save it as form

# Check if form data is valid (server-side)
if form.is_valid():

# Isolate the task from the 'cleaned' version of form data

# Redirect user to list of tasks

else:

# If the form is invalid, re-render the page with existing information.
"form": form
})

})

A quick note: in order to redirect the user after a successful submission, we need a few more imports:

from django.urls import reverse
from django.http import HttpResponseRedirect

## Sessions

At this point, we’ve successfully built an application that allows us to add tasks to a growing list. However, it may be a problem that we store these tasks as a global variable, as it means that all of the users who visit the page see the exact same list. In order to solve this problem we’re going to employ a tool known as sessions.

Sessions are a way to store unique data on the server side for each new visit to a website.

To use sessions in our application, we’ll first delete our global tasks variable, then alter our index function, and finally make sure that anywhere else we had used the variable tasks, we replace it with request.session["tasks"]

def index(request):

# Check if there already exists a "tasks" key in our session

# If not, create a new list

})

if request.method == "POST":

# Take in the data the user submitted and save it as form

# Check if form data is valid (server-side)
if form.is_valid():

# Isolate the task from the 'cleaned' version of form data

# Redirect user to list of tasks
else:

# If the form is invalid, re-render the page with existing information.

Finally, before Django will be able to store this data, we must run python manage.py migrate in the terminal. Next week we’ll talk more about what a migration is, but for now just know that the above command allows us to store sessions.


text:
# [safe_numerics] Formal review starts today

19 messages
Open this post in threaded view
|

## [safe_numerics] Formal review starts today

Open this post in threaded view
|

## Re: [safe_numerics] Formal review starts today

 On 3/1/17 3:36 PM, Andrzej Krzemienski via Boost wrote: Andrzej - why don't we post this on reddit/r/cpp as well? Robert Ramey > Andrzej Krzemieński, review manager. > > _______________________________________________ > Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost> _______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
Open this post in threaded view
|

## Re: [safe_numerics] Formal review starts today

 Ok, here it goes: https://www.reddit.com/r/cpp/comments/5x1z67/boostsafe_numerics_formal_review_starts_today/2017-03-02 1:48 GMT+01:00 Robert Ramey via Boost <[hidden email]>: > On 3/1/17 3:36 PM, Andrzej Krzemienski via Boost wrote: > > Andrzej - why don't we post this on reddit/r/cpp as well? > > Robert Ramey > > Andrzej Krzemieński, review manager. >> >> _______________________________________________ >> Unsubscribe & other changes: http://lists.boost.org/mailman>> /listinfo.cgi/boost >> >> > > _______________________________________________ > Unsubscribe & other changes: http://lists.boost.org/mailman> /listinfo.cgi/boost _______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
Open this post in threaded view
|

## Re: [safe_numerics] Review Part 1 (Documentation)

 In reply to this post by Boost - Dev mailing list AMDG All comments are as of 3bcfabe1cafb8ef6edf08d3bd8730a1555b1c45d General notes: You should have a root index.html that redirects to the top level documentation page. There are two copies of proposal.pdf in the repository. safe_numerics.pdf seems to be out-dated. VS2015: FAIL (as expected) directory structure is not quite boost ready. (needs include/boost/numeric/ instead of just include/) The include paths used in the documentation are a mess. I see at least 6 different variations: - boost/safe_numerics/include/ - boost/safe_numerics/ - safe/numeric/ - boost/numeric/ - safe_numerics/include/ - ../include - ../../include In boostbook, enables C++ syntax highlighting for code snippets.  (This is enabled by default for programlisting, but is used for non-C++ content enough that it needs to be specified.) Introduction: "Since the problems and their solution are similar, We'll..." "We" should not be capitalized. "...the results of these operations are guaranteed to be either arithmetically correct or invoke an error" "either ... or ..." here has a noun on one side and a verb on the other.  Try "... either to be ... or to invoke ..." "#include " I believe that this should be "safe_numerics" (with an "s") "Enforce of other program requirements using ranged integer types." Delete "of" "The library includes the types safe_range(Min, Max) and safe_literal(N)" These don't look like any C++ type I've ever seen unless they're macros. tutorial/1.html "When this occurs, Most" lowercase "Most" "When this occurs, Most C++ compilers will continue to execute with no indication that the results are wrong" Is it the compiler that continues to execute or is it the program built by the compiler? "        // converts variables to int before evaluating he expression!" s/he/the/ "The solution is to replace instances of char type with safe type" There are no char's in this example. tutorial/2.html: "This is a common problem with for loops" Is this really true?  The most common pattern of integer for loops is for(i=0;i tutorial/7.html         std::cout << x / y;         std::cout << " error detected!" << std::endl; Should this be "NOT detected"? eliminate_runtime_penalty.html: The name trap_exception doesn't convey the meaning of causing a compile-time error to me.  To me the term 'trap' implies a signal handler. eliminate_runtime_penalty/1.html: The links for native, automatic, and trap_exception are broken. eliminate_runtime_penalty/3.html     throw_exception // these variables need to need to what? integer.html: "std::numeric_limits.is_integer" should be "::is_integer" safe_numeric_concept.html: "However, it would be very surprising if any implementation were to be more complex that O(0);" I think you mean O(1).  O(0) means that it takes no time at all. "... all C++ operations permitted on it's base type..." s/it's/its/ "( throw exception, compile time trap, etc..)" Delete the leading space. promotion_policy.html: "auto sz = sx + y; // promotes expression type to a safe which requires no result checking is guaranteed not to overflow." The line wrapping ends up uncommented. What happens for binary operators when the arguments have different promotion policies?  Is it an error? Does the implementation randomly pick one?  Is there some kind of precedence rule for promotion policies? (Note: the same thing applies to exception policies) exception_policy.html: "EP | A type that full fills the requirements of an ExceptionPollicy" s/full fills/fulfills/, s/ExceptionPollicy/ExceptionPolicy/ "EP::underflow_error(const char * message)" Underflow is a floating point error that happens when the value is too close to 0.  (INT_MIN - 1) is an overflow error, not an underflow error. "template boost::numeric::no_exception_support" What do the arguments mean?  According to the table, there a 6 functions, not 3. safe.html: "T | Underlying type from which a safe type is being derived" "derived" has a specific meaning in C++ which is not what you mean. "...at runtime if any of several events result in an incorrect arithmetic type." It isn't the type that's incorrect, is it? "If one wants to switch between save and built-in types ..." s/save/safe/ "this type of code will have to be fixed so that implicit conversions to built-in types do not occur" So are explicit casts allowed? "This is because there is no way to guarantee that the expression i * i" The second 'i' seems to be outside the block. "This can be justified by the observe" This sentence is incomplete. "This can be done by specifying a non-default type promotion policy automatic" Should be "policy, automatic."  Also, automatic should probably be "All the work is done at compile time - checking for exceptions necessary (input is of course an exception)" I can't parse this sentence.  Also, the '-' should be an em-dash, I think. safe_range.html: "MIN | must be non-integer literal" I think this is supposed to be "non-negative integer" Also, this is only true for safe_unsigned_range. It would by weird if safe_signed_range didn't accept negative arguments. #include The directory safe/numeric/ doesn't exist.     safe_unsigned_range<7, 24> i missing ';' static_assert(std::is_same); Syntax error: expected '>' befor ')' Also, safe is defined in safe_integer.hpp which is not #included. promotion_policies/native.html: "It's main function is to trap incorrect..." s/It's/Its/ promotion_policies/cpp.html "...we can force the evaluation of C++ expressions test environment..." "...expressions /in the/ test..." Unless I'm misunderstanding something, the use of trap_exception will fail to compile at: d *= velocity; "Note the usage of the compile time trap policy in order to detect at compile time any possible error conditions. As I write this, this is still being refined. Hopefully this will be available by the time you read this." This comment seems out-dated. exception_policies.html: "no_exception_support" So now we have 4 parameters? exception_policies/trap_exception.html: "This exception policy will trap at compile time any operation COULD result in a runtime exception" There's a missing word here.  "...compile time /if/ any..." is one possible fix. exception_policies/no_exception_support.html Template Parameters table: waaaaaay too many O's. Also, the first two parameters (no exception and uninitialized) are missing. library_implementation.html: "correct bugs in it, or understand it's limitations" s/it's/its/ interval.html: boost/numeric/interval.hpp and boost::numeric::interval are already taken by Boost.Interval. checked_result.html: "checked_result(e, msg)" 'e' was not defined. "static_cast(c) | R | extract wrapped value - asserts if not possible" I think this is supposed to return the message as 'const char *' not the value as 'R'. exception_type.html: "dispatch(overflow_error, "operation resulted in overflow");" The template parameter EP is missing. rationale.html: "2. Can safe types be used as drop-in replacement for built-in types?" replacements (plural) "#include   typedef safe_t int16_t;" This may or may not compile as it is unspecified whether cstdint defines ::int16_t. In Christ, Steven Watanabe _______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
Open this post in threaded view
|

## Re: [safe_numerics] Review Part 1 (Documentation)

Open this post in threaded view
|

## Re: [safe_numerics] Review Part 1 (Documentation)

 AMDG On 03/02/2017 03:47 PM, Robert Ramey via Boost wrote: > On 3/2/17 12:12 PM, Steven Watanabe via Boost wrote: >> >> >> The include paths used in the documentation are a mess. >> I see at least 6 different variations: >> - > > Hmmm - where - in the documentation? In the examples? or?. >   This was just from reading the html documentation. the code taken from example/ constently uses ../include/ (probably because it was actually tested and this variation is one that works). The reference sections under Type Requirements and Types have the most variations such as: Header #include Header #include >> >> In boostbook, enables C++ >> syntax highlighting for code snippets.  (This is >> enabled by default for programlisting, but >> is used for non-C++ content enough that it needs >> to be specified.) > Hmmm - right now I'm using program listing and it looks good - syntax is > colorized.  For inline I'm using without the language.  Are > you suggesting that I change the inline to   Yes.  This is just a minor stylistic detail. The only real difference is that it will change the color of int in inline code. > > >> "However, it would be very surprising if any implementation were to be >> more complex that O(0);" >> I think you mean O(1).  O(0) means that it takes no time at all. > Hmm - to me O(0) is fixed time while O(1) is time proportional to x^1. > But I'll rephrase the O() notation which is confusing in this context. > The formal definition of O() is f(x) \in O(g(x)) iff. \exists C, x_0: \forall x > x_0: |f(x)| <= |Cg(x)| If g(x) = 0, then this reduces to \exists x_0 \forall x > x_0: f(x) = 0 i.e. the running time is zero. If g(x) = 1, then we have \exists x_0 \forall x > x_0: |f(x)| <= |C| meaning that the running time is less than some constant, regardless of the value of x. ...which brings us to the real problem with using big-O here: what is x?  For sequence algorithms, x is the length of the sequence, but there's nothing like that here. >> >> What happens for binary operators when the arguments >> have different promotion policies?  Is it an error? >> Does the implementation randomly pick one?  Is there >> some kind of precedence rule for promotion policies? >> (Note: the same thing applies to exception policies) > > In both cases: >     at least one policy must be non void >     if both are non void they must be equal > > I'll clarify this. > Err, what is a void policy? >> >> "EP::underflow_error(const char * message)" >> Underflow is a floating point error that happens >> when the value is too close to 0.  (INT_MIN - 1) >> is an overflow error, not an underflow error. > > Right.  There is no underflow error thrown in the current code. I found one use (probably accidental) at checked.hpp:410. > > >> Also, safe is defined in safe_integer.hpp which is not #included. > > this is included by safe_range.hpp.  But I agree that if I use > safe<..> I should include safe_integer.hpp even though it's > redundent. safe_range.hpp only includes safe_base.hpp. The only reason I noticed this was that Intellisense highlighted safe as undefined. > >> >> promotion_policies/cpp.html >> >> Unless I'm misunderstanding something, the use >> of trap_exception will fail to compile at: >> d *= velocity; > > > > ....  I guess this illustrates the impossibility > for normal people to actually write demonstrably correct code. > Tell me about it: https://github.com/boostorg/random/blob/develop/include/boost/random/uniform_int_distribution.hpp#L93> > > Ahhh - finally I see your point.  assignment using d as > an accumuator loses the range calculated at compile time > so subsequent operations can't be guaranteed to not > overflow. > Yeah.  This makes it a bit inconvenient to use trap_exception with anything other than a strict functional style. In Christ, Steven Watanabe _______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
Open this post in threaded view
|

## Re: [safe_numerics] Review Part 1 (Documentation)

 On 3/2/17 4:49 PM, Steven Watanabe via Boost wrote: > AMDG >> ....  I guess this illustrates the impossibility >> for normal people to actually write demonstrably correct code. ... without the help of something like this. > Tell me about it: > https://github.com/boostorg/random/blob/develop/include/boost/random/uniform_int_distribution.hpp#L93I took a look at this, and it looks good to me. > >> Ahhh - finally I see your point.  assignment using d as >> an accumuator loses the range calculated at compile time >> so subsequent operations can't be guaranteed to not >> overflow. >> > > Yeah.  This makes it a bit inconvenient to use > trap_exception with anything other than a strict > functional style. Actually this turns out to be a very quite interesting point. I started an example of taking a small micro computer program for controlling a stepper motor and using the compile time trapping facility to tweak the program so that it would guaranteed to not produce an invalid result without invoking any runtime overhead. Things went pretty well until I had to actually update the to position. At this point I had to more than "tweak" the program or give up on my goal of avoiding runtime overhead to guarantee no incorrect behavior.  At that point I suspended work on the example because it failed to illustrate my hope that I could take a legacy program for an foreign processor and make minimal changes to guarantee correctness w/o runtime overhead.  But the experiment was very interesting and useful and I hope to get back to it when I understand the science of computer programming better. Robert Ramey > > In Christ, > Steven Watanabe > > > _______________________________________________ > Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost> _______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
Open this post in threaded view
|

## Re: [safe_numerics] Review Part 2 (Implementation)

Open this post in threaded view
|

## Re: [safe_numerics] Review Part 2 (Implementation)

Open this post in threaded view
|

## Re: [safe_numerics] Review Part 2 (Implementation)

 2017-03-07 18:32 GMT+01:00 Robert Ramey via Boost <[hidden email]>: 247: >>         using result_base_type = typename boost::mpl::if_c< >>             std::numeric_limits::is_signed >>             || std::numeric_limits::is_signed, >>             std::intmax_t, >>             std::uintmax_t >>         >::type; >> Why division doesn't use calculate_max_t like multiplication >> deserves some explanation.  Division can overflow >> too (numeric_limits::max() / 1). >> > > Hmmm - I'm sure it's because I've presumed that the result > can aways be contained in the same size type as the number > being divide.  That t / x <= t - and divide by zero is > checked separately. Am I wrong about this? > I am not sure if this is what Steve meant, but:   int x = INT_MIN;   int y = -1;   int a = x / y; // overflows! safe does a check for this condition, but I find it quite surprising that it throws a domain_error rather than overflow_error. How do you make a call whether it is an overflow or a domain error? For mathematical ints dividing -2147483648 by -1 is well defined. Regards, &rzej; _______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
Open this post in threaded view
|

## Re: [safe_numerics] Review Part 2 (Implementation)

Open this post in threaded view
|

## Re: [safe_numerics] Review Part 2 (Implementation)

 In reply to this post by Boost - Dev mailing list On 3/7/17 11:33 AM, Andrzej Krzemienski via Boost wrote: > safe does a check for this condition, but I find it quite surprising > that it throws a domain_error rather than overflow_error. How do you make a > call whether it is an overflow or a domain error? For mathematical ints > dividing -2147483648 by -1 is well defined. Truth is I didn't take a whole lot of care in deciding which one to use. In this case, I think your right that overflow would be a better choice. _______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
Open this post in threaded view
|

## Re: [safe_numerics] Review Part 3 (Tests + Summary)

 In reply to this post by Boost - Dev mailing list AMDG I vote to *ACCEPT* safe_numerics into Boost. The following issues *must* be resolved before inclusion: - Incorrect results for division (see below) - Linker errors from multiple definition (see below) - Name conflict for interval - The whole mess with automatic.  (Probably either allow   it to see the range of safe_base somehow or remove it.) - Test cases must verify results, not just exception or not - The precise rules for determining whether an operator   throws must be specified.  (My preferred definition:   An operator throws iff. it is mathematically undefined   or the mathematical result cannot be represented in the   result type.) All comments are as of 3bcfabe1cafb8ef6edf08d3bd8730a1555b1c45d The tests for the most part seem to check only whether the operation succeeds or fails.  They don't check whether the result is actually correct or not. test_z.cpp appears to be entirely #if 0'd test0.cpp doesn't seem to do anything that  isn't handled by the main tests. test_divide.hpp:129:                 assert(result == unsafe_result); unsafe_result is uninitialized.  (Most other uses are commented out) test_values.hpp: This is missing 0 which is kind of an important case. I've attached my own test case for +-*/. There's some behavior that I consider a little odd which I noted on lines 64-72.  Also it shows some incorrect results for division with automatic and negative [signed] char. for example: generic_test.cpp(76): error: in "test_div": check base_value(f(t, u)) == expected has failed [1 != 0] Failure occurred in a following context:     -85 [safe_base] / 3464536379 [safe_base] -> [safe_base<__int64,-9223372036854775808,9223372036854775807,automatic>] I had to make a couple minor edits to get the library to compile with vc15 (just released).  Patch attached. When I include the entire library in two translation units and link them together I get errors: test1.obj : error LNK2005: "class std::basic_ostream > & __cdecl std::operator<<(class std::basic_ostream > &,struct boost::numeric::checked_result const &)" (??$?6C@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@ABU?$checked_result@C@numeric@boost@@@Z) already defined in include_all.obj test1.obj : error LNK2005: "class std::basic_ostream > & __cdecl std::operator<<(class std::basic_ostream > &,struct boost::numeric::checked_result const &)" (??$?6E@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@ABU?$checked_result@E@numeric@boost@@@Z) already defined in include_all.obj test1.obj : error LNK2005: "class std::basic_ostream > & __cdecl std::operator<<(class std::basic_ostream > &,struct boost::numeric::interval const &)" (??$?6E@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@ABU?$interval@E@numeric@boost@@@Z) already defined in include_all.obj test1.obj : error LNK2005: "class std::basic_ostream > & __cdecl std::operator<<(class std::basic_ostream > &,struct boost::numeric::interval const &)" (??$?6C@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@ABU?$interval@C@numeric@boost@@@Z) already defined in include_all.obj   I tried using boost::format(...) % safe() and it fails because your operator% matches.  I notice that you have checks for ostream and istream with the shift operators, but it would really be better to make it more generic by checking is_arithmetic (or perhaps std::numeric_limits::is_specialized) on all the operators. In Christ, Steven Watanabe _______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost generic_test.cpp (8K) Download Attachment safe_numerics_vc15.patch (1K) Download Attachment
Open this post in threaded view
|

## Re: [safe_numerics] Formal review starts today

 In reply to this post by Boost - Dev mailing list > -----Original Message----- > From: Boost [mailto:[hidden email]] On Behalf Of Andrzej Krzemienski via Boost > Sent: 01 March 2017 23:37 > To: [hidden email]; [hidden email] > Cc: Andrzej Krzemienski > Subject: [boost] [safe_numerics] Formal review starts today > > Hi Everyone, > Today, on March 2nd (or tomorrow, depending on your timezone), is the start > of the formal review of safe_numerics library by Robert Ramey. The review > will run till March 11th. I will be serving as review manager. > > safe_numerics is a set of drop-in replacements for the built-in integer > types, which make the guarantee that the results of operations are either > correct according to the rules of integer arithmetic or report a > diagnosable error (rather than offering modulo arithmetic results, or > resulting in undefined behavior, or returning incorrect results as in the > case of signed vs. unsigned comparisons). > > The library can be found on GitHub: > https://github.com/robertramey/safe_numerics/> > Online docs: > http://htmlpreview.github.io/?https://github.com/robertramey/safe_numerics/> master/doc/html/index.html > > Formal Review comments can be posted publicly on the mailing list or Boost > Library Incubator , or sent privately to the review > manager, that is myself. > > Here are some questions you might want to answer in your review: > >    - What is your evaluation of the design? Complicated to use (compared to int), and very, very complicated to write. But that is a consequence of the daft design of the C language. The language also doesn't allow use of hardware to handle overflow (and underflow) and doesn't have arrays etc as first class citizens. I don't believe that it is really a idiot-proof drop-in replacement for the built-in integral types, but it will be fine to be used for new projects, especially as it needed the fancy features of C++14. I agree that explicit conversions are the Right Thing, but they do carry a cost to the users - the need to understand the issues and take care with construction and assignment because this is a User Defined Type (UDT) and the special-case privileges of built-in do not apply (another daft design decision).  Floating-point and fixed-point UDT have proved unintuitive to use because of explicit conversions; there are big elephant traps awaiting the unwary. Costly at compile time because of the number of libraries included, but that's a cost worth paying. I like that the infrastructure might be extended to other than integral types. >    - What is your evaluation of the implementation? Above my pay grade. >    - What is your evaluation of the documentation? Good exposition of the problems and solutions. Good examples. Links to source of examples code would be *very* useful.  Starting with an example is the most common way of 'getting started'. Will using "" file specification #include "../include/safe_range.hpp" instead of <> #include <../include/safe_range.hpp> cause trouble for users trying to use/modify the examples in Boost or their own folder position? The common need for overflow (or underflow) to become 'saturation' == max_value (or min_value) is not an option (but then it is arithmetically 'wrong', I suppose ;-)) >    - What is your evaluation of the potential usefulness of the library? Very valuable to make programs that 'always work' instead of 'mostly work'. Users might appreciate a list of compiler versions that really do work. Sadly 'Compliant C++14' is a bit fuzzy.  (Should become clearer if accepted and test matrix visible). A good effort at working round fundamental C language defects. >    - Did you try to use the library? With what compiler? Did you have any    problems? Had a very brief try with VS 2015 with /std:c++latest added to command line (to try to ensure C++14 compliance) but am stuck with 1>j:\cpp\safe_numeric\safe_numeric\include\interval.hpp(107): error C2737: 'boost::numeric::anonymous-namespace'::failed_result': 'constexpr' object must be initialized 1>j:\cpp\safe_numeric\safe_numeric\include\safe_base_operations.hpp(131): error C2244: 'boost::numeric::safe_base::operator =': unable to match function definition to an existing declaration But I am sure that this is entirely my fault, but I'm out of my time allotted to this review. Also - Is this warning(s) avoidable/relevant/quietable? j:\cpp\safe_numeric\safe_numeric\include\safe_base.hpp(233): warning C4814: 'boost::numeric::safe_base::operator =': in C++14 'constexpr' will not imply 'const'; consider explicitly specifying 'const' I feel that all warnings should be avoided or supressed using push'n'pop pragmas. >    - How much effort did you put into your evaluation? A glance?  A quick  reading. >    - Are you especially knowledgeable about the problem domain? No. > Do you think the library should be accepted as a Boost library? Yes. Paul PS I noted a few typos in documentation (though I doubt these have escaped Steven's fine-tooth-combing ;-). multiplication etc. . C/C++ often automatically  - extraneous . similar, We'll  - should be lower case w. the expression will yield the correct mathematical result - missing . trap at compiler time all operations which might fail at runtime.  - compile-time (Better to use compile-time and run-time throughout? Inventing new words is unnecessary and hyphenating is good for readbility) This solution is simple, Just replace instances    - lower case j parameters are guarenteed to meet requirements when - guaranteed our program compiles without error - even when using the trap_exception exception policy  - missing . We only needed to change two lines of code to achieve our goal missing . ( throw exception, compile time trap, etc..) no implementation should return an arithmetically incorrect result.  - extraneous space after ( and missing . and new sentence No implementation ... C++ operations permitted on it's base type - should be its  (possessive!) --- Paul A. Bristow Prizet Farmhouse Kendal UK LA8 8AB +44 (0) 1539 561830 _______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
Open this post in threaded view
|

## Re: [safe_numerics] Formal review starts today

Open this post in threaded view
|

## Re: [safe_numerics] Formal review starts today

 > -----Original Message----- > From: Boost [mailto:[hidden email]] On Behalf Of Robert Ramey via Boost > Sent: 09 March 2017 18:32 > To: [hidden email] > Cc: Robert Ramey > Subject: Re: [boost] [safe_numerics] Formal review starts today > > On 3/9/17 7:23 AM, Paul A. Bristow via Boost wrote: > > >> Here are some questions you might want to answer in your review: > >>    - What is your evaluation of the design? > > Complicated to use (compared to int), > > Hmmm - a major design goal is that it be a no-brainer to use.  I'd like > to see you exand a little on this comment. One needs to fully understand static_cast - it's an unintuitive name for something that has unexpectedly complicated implications.     > > But that is a consequence of the daft design of the C language. > > tl;dr; > > I want to defend the C language design. My first exposure to C was in > 1980?  I was introduced to Ratfor which was a fortran implemented C like > language introduced in the Plauger book "Software Tools".  After that I > lusted after a C language tool.  The machine I had at my disposal was a > Data General Eclipse - a 16 bit architecture.  I got a hold source code > for a compiler for the Z80 and managed to port it to the DG machine. > Then I managed to compile the standard source which my compiler.  I was > hooked!  The C language then was the world's first "portable assembler". >   This was huge at the time.   I can't resist saying that my reaction to learning of C design philosophy was LOL :-( But programmers liked quick'n'dirty and being trusted  (the biggest mistake of all), a host of .edu starting teaching C, and like FORTRANs bottomless pit of working subroutines, it was unstoppable. And so here we are putting Band-Aids on the C++ and STL Band-Aids*. > I'm hoping to bridge two worlds here.  I'm not hopeful.  I'm a sucker for lost causes. I'm optimistic.  I'm not the only one getting cross with 'mostly work' programs, and as you observe, people will get *really cross* with 'mostly work' killer cars. Chris Kormanyos has publicised how to use recent C++ on bare-metal in his book Real-Time C++. > > Users might appreciate a list of compiler versions that really do work. They really *must* have such a list. > >>    - Did you try to use the library? With what compiler? Did you have any    problems? > > Had a very brief try with VS 2015  and failed. John Maddock has since explained why nothing I tried worked.  I'm a bit shocked that it hasn't been tested on MSVC.  My acceptance was on the assumption that it would work.  It really must be portable over recent GCC, Clang and MSVC at the very minimum. I suggest that we should pause the review until you adopt John's patches and reissue the review code and then restart the review. It'll be a bit poor to accept the library until a few people confirm it's working on MSVC. Keep going! Paul * Band-Aid Trademark of Johnson and Johnson ;-) --- Paul A. Bristow Prizet Farmhouse Kendal UK LA8 8AB +44 (0) 1539 561830 _______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
Open this post in threaded view
|

## Re: [safe_numerics] Formal review starts today

 2017-03-11 15:27 GMT+01:00 Paul A. Bristow via Boost <[hidden email]> : > > -----Original Message----- > > From: Boost [mailto:[hidden email]] On Behalf Of Robert > Ramey via Boost > > Sent: 09 March 2017 18:32 > > To: [hidden email] > > Cc: Robert Ramey > > Subject: Re: [boost] [safe_numerics] Formal review starts today > > > > On 3/9/17 7:23 AM, Paul A. Bristow via Boost wrote: > > > > >> Here are some questions you might want to answer in your review: > > >>    - What is your evaluation of the design? > > > > Complicated to use (compared to int), > > > > Hmmm - a major design goal is that it be a no-brainer to use.  I'd like > > to see you exand a little on this comment. > > One needs to fully understand static_cast - it's an unintuitive name for > something that has unexpectedly complicated implications. > > > > But that is a consequence of the daft design of the C language. > > > > tl;dr; > > > > I want to defend the C language design. My first exposure to C was in > > 1980?  I was introduced to Ratfor which was a fortran implemented C like > > language introduced in the Plauger book "Software Tools".  After that I > > lusted after a C language tool.  The machine I had at my disposal was a > > Data General Eclipse - a 16 bit architecture.  I got a hold source code > > for a compiler for the Z80 and managed to port it to the DG machine. > > Then I managed to compile the standard source which my compiler.  I was > > hooked!  The C language then was the world's first "portable assembler". > >   This was huge at the time. > > I can't resist saying that my reaction to learning of C design philosophy > was LOL :-( > > But programmers liked quick'n'dirty and being trusted  (the biggest > mistake of all), > a host of .edu starting teaching C, and like FORTRANs bottomless pit of > working subroutines, > it was unstoppable. > > And so here we are putting Band-Aids on the C++ and STL Band-Aids*. > > > I'm hoping to bridge two worlds here.  I'm not hopeful.  I'm a sucker > for lost causes. > > I'm optimistic.  I'm not the only one getting cross with 'mostly work' > programs, > and as you observe, people will get *really cross* with 'mostly work' > killer cars. > Chris Kormanyos has publicised how to use recent C++ on bare-metal in his > book Real-Time C++. > > > > Users might appreciate a list of compiler versions that really do work. > > They really *must* have such a list. > > > >>    - Did you try to use the library? With what compiler? Did you have > any    problems? > > > > Had a very brief try with VS 2015  and failed. > > John Maddock has since explained why nothing I tried worked.  I'm a bit > shocked that it hasn't been tested on MSVC.  My acceptance > was on the assumption that it would work.  It really must be portable over > recent GCC, Clang and MSVC at the very minimum. > According to formal Boost criteria, it is sufficient for the library to work on two major compilers. These formal criteria are met by safe_numerics. Of couse, I acknoledge, that formal criteria are not the ony thing in the world. > > I suggest that we should pause the review until you adopt John's patches > and reissue the review code and then restart the review. > From the formal point of view, the two options for this I can see are:    - To conclude the review as rejected, and schedule a new one.    - Accept the library conditionally, and make the fix a hard condition/ It'll be a bit poor to accept the library until a few people confirm it's > working on MSVC. > Accepting the library does not mean it is immediately available in the next Boost release. If the library is accepted conditionally, you would be guaranteed that the users will get MSVC support (if adding this support is doable). Regards, &rzej; _______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost


text:
# Bargaining Problem

The two-person bargaining problem studies how two agents share a surplus that they can jointly generate. It is in essence a payoff selection problem. In many cases, the surplus created by the two players can be shared in many ways, forcing the players to negotiate which division of payoffs to choose. There are two typical approaches to the bargaining problem. The normative approach studies how the surplus should be shared. It formulates appealing axioms that the solution to a bargaining problem should satisfy. The positive approach answers the question how the surplus will be shared. Under the positive approach, the bargaining procedure is modeled in detail as a non-cooperative game. Read all..

## Explanation

[You can read the original article here], Licensed under CC-BY-SA.

The two-person bargaining problem studies how two agents share a surplus that they can jointly generate. It is in essence a payoff selection problem. In many cases, the surplus created by the two players can be shared in many ways, forcing the players to negotiate which division of payoffs to choose. There are two typical approaches to the bargaining problem. The normative approach studies how the surplus should be shared. It formulates appealing axioms that the solution to a bargaining problem should satisfy. The positive approach answers the question how the surplus will be shared. Under the positive approach, the bargaining procedure is modeled in detail as a non-cooperative game.

## The bargaining game

The Nash bargaining solution is the unique solution to a two-person bargaining problem that satisfies the axioms of scale invariance, symmetry, efficiency, and independence of irrelevant alternatives. According to Walker,[1] Nash's bargaining solution was shown by John Harsanyi to be the same as Zeuthen's solution[2] of the bargaining problem.

The Nash bargaining game is a simple two-player game used to model bargaining interactions. In the Nash bargaining game, two players demand a portion of some good (usually some amount of money). If the total amount requested by the players is less than that available, both players get their request. If their total request is greater than that available, neither player gets their request.

Nash (1953) presents a non-cooperative demand game with two players who are uncertain about which payoff pairs are feasible. In the limit as the uncertainty vanishes, equilibrium payoffs converge to those predicted by the Nash bargaining solution.[3]

Rubinstein also modelled bargaining as a non-cooperative game in which two players negotiate on the division of a surplus known as the alternating offers bargaining game.[4] The players take turns acting as the proposer. The division of the surplus in the unique subgame perfect equilibrium depends upon how strongly players prefer current over future payoffs. In the limit as players become perfectly patient, the equilibrium division converges to the Nash bargaining solution.

For a comprehensive discussion of the Nash bargaining solution and the huge literature on the theory and application of bargaining - including a discussion of the classic Rubinstein bargaining model - see Abhinay Muthoo's book Bargaining Theory and Application.[5]

## Formal description

A two-person bargain problem consists of:

• A feasibility set ${\displaystyle F}$, a closed subset of ${\displaystyle \mathbb {R} ^{2}}$ that is often assumed to be convex, the elements of which are interpreted as agreements. ${\displaystyle F}$ is often assumed to be convex because, for any two feasible outcomes, a convex combination (a weighted average) of them is typically also feasible.
• A disagreement, or threat, point ${\displaystyle d=(d_{1},d_{2})}$, where ${\displaystyle d_{1}}$ and ${\displaystyle d_{2}}$ are the respective payoffs to player 1 and player 2, which they are guaranteed to receive if they cannot come to a mutual agreement.

The problem is nontrivial if agreements in ${\displaystyle F}$ are better for both parties than the disagreement point. A solution to the bargaining problem selects an agreement ${\displaystyle \phi }$ in ${\displaystyle F}$.

### Feasibility set

The feasible agreements typically include all possible joint actions, leading to a feasibility set that includes all possible payoffs. Often, the feasible set is restricted to include only payoffs that have a possibility of being better than the disagreement point for the agents that are bargaining.[3]

### Disagreement point

The disagreement point ${\displaystyle d}$ is the value the players can expect to receive if negotiations break down. This could be some focal equilibrium that both players could expect to play. This point directly affects the bargaining solution, however, so it stands to reason that each player should attempt to choose his disagreement point in order to maximize his bargaining position. Towards this objective, it is often advantageous to increase one's own disagreement payoff while harming the opponent's disagreement payoff (hence the interpretation of the disagreement as a threat). If threats are viewed as actions, then one can construct a separate game wherein each player chooses a threat and receives a payoff according to the outcome of bargaining. It is known as Nash's variable threat game.

## Equilibrium analysis

Strategies are represented in the Nash demand game by a pair (x, y). x and y are selected from the interval [d, z], where d is the disagreement outcome and z is the total amount of good. If x + y is equal to or less than z, the first player receives x and the second y. Otherwise both get d; often ${\displaystyle d=0}$.

There are many Nash equilibria in the Nash demand game. Any x and y such that x + y = z is a Nash equilibrium. If either player increases their demand, both players receive nothing. If either reduces their demand they will receive less than if they had demanded x or y. There is also a Nash equilibrium where both players demand the entire good. Here both players receive nothing, but neither player can increase their return by unilaterally changing their strategy.

In Rubinstein's alternating offers bargaining game,[4] players take turns acting as the proposer for splitting some surplus. The division of the surplus in the unique subgame perfect equilibrium depends upon how strongly players prefer current over future payoffs. In particular, let d be the discount factor, which refers to the rate at which players discount future earnings. That is, after each step the surplus is worth d times what it was worth previously. Rubinstein showed that if the surplus is normalized to 1, the payoff for player 1 in equilibrium is 1/(1+d), while the payoff for player 2 is d/(1+d). In the limit as players become perfectly patient, the equilibrium division converges to the Nash bargaining solution.

## Bargaining solutions

Various solutions have been proposed based on slightly different assumptions about what properties are desired for the final agreement point.

### Nash bargaining solution

John Nash proposed[6] that a solution should satisfy certain axioms:

1. Invariant to affine transformations or Invariant to equivalent utility representations
2. Pareto optimality
3. Independence of irrelevant alternatives
4. Symmetry

Nash proved that the solutions satisfying these axioms are exactly the points ${\displaystyle (x,y)}$ in ${\displaystyle F}$ which maximize the following expression:

${\displaystyle (u(x)-u(d))(v(y)-v(d))}$

where u and v are the utility functions of Player 1 and Player 2, respectively, and d is a disagreement outcome. That is, players act as if they seek to maximize ${\displaystyle (u(x)-u(d))(v(y)-v(d))}$, where ${\displaystyle u(d)}$ and ${\displaystyle v(d)}$, are the status quo utilities (the utility obtained if one decides not to bargain with the other player). The product of the two excess utilities is generally referred to as the Nash product. Intuitively, the solution consists of each player getting their status quo payoff (i.e., noncooperative payoff) in addition to a share of the benefits occurring from cooperation.[7]:15–16

### Kalai–Smorodinsky bargaining solution

Independence of Irrelevant Alternatives can be substituted with a Resource monotonicity axiom. This was demonstrated by Ehud Kalai and Meir Smorodinsky.[8] This leads to the so-called Kalai–Smorodinsky bargaining solution: it is the point which maintains the ratios of maximal gains. In other words, if we normalize the disagreement point to (0,0) and player 1 can receive a maximum of ${\displaystyle g_{1}}$ with player 2's help (and vice versa for ${\displaystyle g_{2}}$), then the Kalai–Smorodinsky bargaining solution would yield the point ${\displaystyle \phi }$ on the Pareto frontier such that ${\displaystyle \phi _{1}/\phi _{2}=g_{1}/g_{2}}$ .

### Egalitarian bargaining solution

The egalitarian bargaining solution, introduced by Ehud Kalai,[9] is a third solution which drops the condition of scale invariance while including both the axiom of Independence of irrelevant alternatives, and the axiom of resource monotonicity. It is the solution which attempts to grant equal gain to both parties. In other words, it is the point which maximizes the minimum payoff among players. Kalai notes that this solution is closely related to the egalitarian ideas of John Rawls.

### Comparison table

NamePareto-optimalitySymmetryScale-invarianceIrrelevant-independenceResource-monotonicityPrinciple
Nash (1950)Maximizing the product of surplus utilities
Kalai-Smorodinsky (1975)Equalizing the ratios of maximal gains
Kalai (1977)Maximizing the minimum of surplus utilities

## Experimental solutions

A series of experimental studies[10] found no consistent support for any of the bargaining models. Although some participants reached results similar to those of the models, others did not, focusing instead on conceptually easy solutions beneficial to both parties. The Nash equilibrium was the most common agreement (mode), but the average (mean) agreement was closer to a point based on expected utility.[11] In real-world negotiations, participants often first search for a general bargaining formula, and then only work out the details of such an arrangement, thus precluding the disagreement point and instead moving the focal point to the worst possible agreement.

## Applications

Kenneth Binmore has used the Nash bargaining game to explain the emergence of human attitudes toward distributive justice.[12][13] He primarily uses evolutionary game theory to explain how individuals come to believe that proposing a 50–50 split is the only just solution to the Nash bargaining game. Herbert Gintis supports a similar theory, holding that humans have evolved to a predisposition for strong reciprocity but do not necessarily make decisions based on direct consideration of utility.[14]

## Bargaining solutions and risk-aversion

Some economists have studied the effects of risk aversion on the bargaining solution. Compare two similar bargaining problems A and B, where the feasible space and the utility of player 1 remain fixed, but the utility of player 2 is different: player 2 is more risk-averse in A than in B. Then, the payoff of player 2 in the Nash bargaining solution is smaller in A than in B.[15]:303–304 However, this is true only if the outcome itself is certain; if the outcome is risky, then a risk-averse player may get a better deal as proved by Alvin E. Roth and Uriel Rothblum[16]

## References

1. Walker, Paul (2005). "History of Game Theory". Archived from the original on 2000-08-15. Retrieved 2008-05-03.
2. Zeuthen, Frederik (1930). Problems of Monopoly and Economic Warfare.
3. Nash, John (1953-01-01). "Two-Person Cooperative Games". Econometrica. 21 (1): 128–140. doi:10.2307/1906951. JSTOR 1906951.
4. Rubinstein, Ariel (1982-01-01). "Perfect Equilibrium in a Bargaining Model". Econometrica. 50 (1): 97–109. CiteSeerX 10.1.1.295.1434. doi:10.2307/1912531. JSTOR 1912531.
5. Nash, John (1950). "The Bargaining Problem". Econometrica. 18 (2): 155–162. doi:10.2307/1907266. JSTOR 1907266.
6. Muthoo, Abhinay (1999). Bargaining theory with applications. Cambridge University Press.
7. Kalai, Ehud & Smorodinsky, Meir (1975). "Other solutions to Nash's bargaining problem". Econometrica. 43 (3): 513–518. doi:10.2307/1914280. JSTOR 1914280.
8. Kalai, Ehud (1977). "Proportional solutions to bargaining situations: Intertemporal utility comparisons" (PDF). Econometrica. 45 (7): 1623–1630. doi:10.2307/1913954. JSTOR 1913954.
9. Schellenberg, James A. (1 January 1990). "'Solving' the Bargaining Problem" (PDF). Mid-American Review of Sociology. 14 (1/2): 77–88. Retrieved 28 January 2017.
10. Felsenthal, D. S.; Diskin, A. (1982). "The Bargaining Problem Revisited: Minimum Utility Point, Restricted Monotonicity Axiom, and the Mean as an Estimate of Expected Utility". Journal of Conflict Resolution. 26 (4): 664–691. doi:10.1177/0022002782026004005.
11. Binmore, Kenneth (1998). Game Theory and the Social Contract Volume 2: Just Playing. Cambridge: MIT Press. ISBN 978-0-262-02444-0.
12. Binmore, Kenneth (2005). Natural Justice. New York: Oxford University Press. ISBN 978-0-19-517811-1.
13. Gintis, H. (11 August 2016). "Behavioral ethics meets natural justice". Politics, Philosophy & Economics. 5 (1): 5–32. doi:10.1177/1470594x06060617.
14. Osborne, Martin (1994). A Course in Game Theory. MIT Press. ISBN 978-0-262-15041-5.
15. Roth, Alvin E.; Rothblum, Uriel G. (1982). "Risk Aversion and Nash's Solution for Bargaining Games with Risky Outcomes". Econometrica. 50 (3): 639. doi:10.2307/1912605. JSTOR 1912605.
© 2019 raptorfind.com. Imprint, All rights reserved.


text:
# Pendulum by Léon Foucault

## Léon Foucault, Paris1851

### Deutsches Museum

In 1851, Léon Foucault used a pendulum in the Pantheon im Paris to prove the Earth’s rotation on its axis in relation of the fixed stars in the sky.
The pendulum is set in motion at 9.00 a.m. and then swings freely. You can see the progression of the Earth as the pendulum slowly swings towards the angles indicated on the floor. At the North or South Pole, at 90° latitude north and south, respectively, the perpendicular plane of swings of the pendulum changes in relation to the Earth’s surface. The Earth thus rotates beneath the plane of the pendulum’s suspension once every 24 hours.
At the Equator, 0° latitude, the rotation of the plane of the pendulum in relation to the Earth is an intermediate value within the extremes at the Pole and at the Equator. In Munich, the plane of the pendulum rotates by appproximately 11.15° per hour.
Pendulum wire length: 60 m
Mass of the pendulum ball: 30 kg
Demonstration starts at 9.00 a.m.