text:
Language:   Search:   Contact
Zentralblatt MATH has released its new interface!
For an improved author identification, see the new author database of ZBMATH.

Query:
Fill in the form and click »Search«...
Format:
Display: entries per page entries
Zbl 0868.39006
Domshlak, Yuri
Oscillatory properties of linear difference equations with continuous time.
(English)
[J] Differ. Equ. Dyn. Syst. 1, No.4, 311-324 (1993). ISSN 0971-3514; ISSN 0974-6870/e

Summary: We establish the analogues of classical Sturmian theorems (comparison theorem, oscillation theorem, zeros-separation theorem) for linear difference equations (and inequalities) with continuous time (DECT) $$x[p(t)]- a(t)x(t)+ \sum^N_{k=1} b_k(t) x[r_k(t)]=0, \qquad t\geq t_0.$$ As a result we obtain: \par (a) Sharp conditions for the oscillation of all solutions of the above equation (with $N=1$ and $N=2$) in terms of its coefficients; \par (b) Upper estimates (and some lower estimates as well) for the length of the sign-preservation intervals for solutions; \par (c) Some properties for the DECTs with no regular oscillatory solutions.
MSC 2000:
*39A12 Discrete version of topics in analysis
39A10 Difference equations
26D20 Analytical inequalities involving real functions

Keywords: difference inequalities; comparison theorem; linear difference equations with continuous time; Sturmian theorems; oscillation theorem; zeros-separation theorem; oscillatory solutions

Highlights
Master Server

format: plain


text:
Volume 15, Issue 1
Piecewise Rational Approximations of Real Algebraic Curves
DOI:

J. Comp. Math., 15 (1997), pp. 55-71

Published online: 1997-02

Preview Full PDF 489 1484
Export citation

Cited by

• Abstract

We use a combination of both algebraic and numerical techniques to construct a $C^1$-continuous, piecewise $(m,n)$ rational $\epsilon$-approximation of a real algebraic plane curve of degree $d$. At singular points we use the classical Weierstrass Preparation Theorem and Newton power series factorizations, based on the technique of Hensel lifting. These, together with modified rational Pad\'{e} approximations, are used to efficiently construct locally approximate, rational parametric representations for all real branches of an algebraic plane curve. Besides singular points we obtain an adaptive selection of simple points about which the curve approximations yield a small number of pieces yet achieve $C^1$ continuity between pieces. The simpler cases of $C^{-1}$ and $C^0$ continuity are also handled in a similar manner. The computation of singularity, the approximation error bounds and details of the implementation of these algorithms are also provided.

• Keywords

@Article{JCM-15-55, author = {}, title = {Piecewise Rational Approximations of Real Algebraic Curves}, journal = {Journal of Computational Mathematics}, year = {1997}, volume = {15}, number = {1}, pages = {55--71}, abstract = { We use a combination of both algebraic and numerical techniques to construct a $C^1$-continuous, piecewise $(m,n)$ rational $\epsilon$-approximation of a real algebraic plane curve of degree $d$. At singular points we use the classical Weierstrass Preparation Theorem and Newton power series factorizations, based on the technique of Hensel lifting. These, together with modified rational Pad\'{e} approximations, are used to efficiently construct locally approximate, rational parametric representations for all real branches of an algebraic plane curve. Besides singular points we obtain an adaptive selection of simple points about which the curve approximations yield a small number of pieces yet achieve $C^1$ continuity between pieces. The simpler cases of $C^{-1}$ and $C^0$ continuity are also handled in a similar manner. The computation of singularity, the approximation error bounds and details of the implementation of these algorithms are also provided. }, issn = {1991-7139}, doi = {https://doi.org/}, url = {http://global-sci.org/intro/article_detail/jcm/9189.html} }
TY - JOUR T1 - Piecewise Rational Approximations of Real Algebraic Curves JO - Journal of Computational Mathematics VL - 1 SP - 55 EP - 71 PY - 1997 DA - 1997/02 SN - 15 DO - http://doi.org/ UR - https://global-sci.org/intro/article_detail/jcm/9189.html KW - AB - We use a combination of both algebraic and numerical techniques to construct a $C^1$-continuous, piecewise $(m,n)$ rational $\epsilon$-approximation of a real algebraic plane curve of degree $d$. At singular points we use the classical Weierstrass Preparation Theorem and Newton power series factorizations, based on the technique of Hensel lifting. These, together with modified rational Pad\'{e} approximations, are used to efficiently construct locally approximate, rational parametric representations for all real branches of an algebraic plane curve. Besides singular points we obtain an adaptive selection of simple points about which the curve approximations yield a small number of pieces yet achieve $C^1$ continuity between pieces. The simpler cases of $C^{-1}$ and $C^0$ continuity are also handled in a similar manner. The computation of singularity, the approximation error bounds and details of the implementation of these algorithms are also provided.


text:
×
Get Full Access to College Physics For Ap® Courses - 1 Edition - Chapter 6 - Problem 3
Get Full Access to College Physics For Ap® Courses - 1 Edition - Chapter 6 - Problem 3

×

# If you wish to reduce the stress (which is related to centripetal force) on high-speed

ISBN: 9781938168932 372

## Solution for problem 3 Chapter 6

College Physics for AP® Courses | 1st Edition

• Textbook Solutions
• 2901 Step-by-step solutions solved by professors and subject experts
• Get 24/7 help from StudySoup virtual teaching assistants

College Physics for AP® Courses | 1st Edition

4 5 1 411 Reviews
19
4
Problem 3

If you wish to reduce the stress (which is related to centripetal force) on high-speed tires, would you use large- or smalldiameter tires? Explain.

Step-by-Step Solution:
Step 1 of 3

PHYS 242 BLOCK 4 NOTES Sections 27.1 to 27.7, 27.9 Consider a freely-pivoted compass needle(or a bar magnet) in the earth’s magnetic field. The magnetized object’s north pole (N-pole) points geographically north and itssouth pole (S-pole) points geographicallysouth (neither exactly so). Consideringthe earth as a magnet,currently its south magneticpole is located near its north geographic pole and vice versa (see Fig.27.3). F = q E defines the electricfield E and F = qυ × B defines the magnetic field B . This vector 0 0 equation tells us that anynon-zeroF is perpendicular toboth υ and B . Also, F is in the same direction as υ → → → × B for positive charge and oppositeυ × B for negative charge (Fig. 27.8). → The magnitude of the magnetic force F is F ⊥ |q|υB⊥s. Thus F is zero if the charged object moves paφ = 0) or antiparalle( = 180˚) to the external magnetic field (seeFig. 27.6a) and F is greatest when the object mov( = 90˚) to the external magnetic field (see Fig. 27.6c). → F is the magnetic force (in N) on the object andq is the object’s charge (in C, where 1 C≡ 1 A·s). → m → N υ is the object’s selocity (in ) and B is the external magnetA·m).eld (in T = tesla, where 1 T = 1 Cover up the solution and carefully work Example 27.1. Magnetic field lines: 1. They are used to visualize the magnetic field. 2. B is tangent to a magnetic field line at

Step 2 of 3

Step 3 of 3

##### ISBN: 9781938168932

The answer to “If you wish to reduce the stress (which is related to centripetal force) on high-speed tires, would you use large- or smalldiameter tires? Explain.” is broken down into a number of easy to follow steps, and 24 words. Since the solution to 3 from 6 chapter was answered, more than 303 students have viewed the full step-by-step answer. This textbook survival guide was created for the textbook: College Physics for AP® Courses, edition: 1. College Physics for AP® Courses was written by and is associated to the ISBN: 9781938168932. The full step-by-step solution to problem: 3 from chapter: 6 was answered by , our top Physics solution expert on 03/09/18, 08:07PM. This full solution covers the following key subjects: . This expansive textbook survival guide covers 34 chapters, and 2282 solutions.

## Discover and learn what students are asking

Calculus: Early Transcendental Functions : Polar Equations of Conics and Keplers Laws
?Consider the polar equation $$r=\frac{4}{1-0.4 \cos \theta}$$ (a) Identify the conic without graphing the equation. (b) Wit

Calculus: Early Transcendental Functions : Second-Order Nonhomogeneous Linear Equations
?Finding a Particular Solution In Exercises 5-10,find a particular solution of the differential equation. y’’ - y’ - 6y = 4

Statistics: Informed Decisions Using Data : Inference about Two Population Standard Deviations
?In Problems 9–14, assume that the populations are normally distributed. Test the given hypothesis. 9. s1 ? s2 at the a = 0.05 level of signif

#### Related chapters

Unlock Textbook Solution


text:
# Geometric median

The geometric median of a discrete set of sample points in a Euclidean space is the point minimizing the sum of distances to the sample points. This generalizes the median, which has the property of minimizing the sum of distances for one-dimensional data, and provides a central tendency in higher dimensions. It is also known as the 1-median.[1]

The geometric median is an important estimator of location in statistics. It is also a standard problem in facility location, where it models the problem of locating a facility to minimize the cost of transportation.

The special case of the problem for three points in the plane (that is, m = 3 and n = 2 in the definition below) is sometimes also known as Fermat's problem; it arises in the construction of minimal Steiner trees, and was originally posed as a problem by Pierre de Fermat to Evangelista Torricelli, who solved it. Its solution is now known as the Fermat point of the triangle formed by the three sample points. The geometric median may in turn be generalized to the problem of minimizing the sum of weighted distances, known as the Weber problem after Alfred Weber's discussion of the problem in his 1909 book on facility location. Some sources instead call Weber's problem the Fermat–Weber problem, but others use this name for the unweighted geometric median problem.

Wesolowsky (1993) provides a survey of the geometric median problem. See Fekete, Mitchell, and Beurer (2003) for generalizations of the problem to non-discrete point sets.

## Definition

Formally, for a given set of m points $x_1, x_2, \dots, x_m\,$ with each $x_i \in \mathbb{R}^n$, the geometric median is defined as

Geometric Median $=\underset{y \in \mathbb{R}^n}{\operatorname{arg\,min}} \sum_{i=1}^m \left \| x_i-y \right \|_2$

Note that argmin means the value of the argument $y$ which minimizes the sum. In this case, it is the point $y$ from where the sum of all Euclidean distances to the $x_i$'s is minimum.

## Properties

• For the 1-dimensional case, the geometric median coincides with the median. This is because the univariate median also minimizes the sum of distances from the points.
• The geometric median is unique whenever the points are not collinear.
• The geometric median is equivariant for Euclidean similarity transformations, including translation and rotation. This means that one would get the same result either by transforming the geometric median, or by applying the same transformation to the sample data and finding the geometric median of the transformed data. This property follows from the fact that the geometric median is defined only from pairwise distances, and doesn't depend on the system of orthogonal Cartesian coordinates by which the sample data is represented. In contrast, the component-wise median for a multivariate data set is not in general rotation invariant, nor is it independent of the choice of coordinates.
• The geometric median has a breakdown point of 0.5.[2] That is, up to half of the sample data may be arbitrarily corrupted, and the median of the samples will still provide a robust estimator for the location of the uncorrupted data.

## Special cases

• For 3 (non-collinear) points, if any angle of the triangle formed by those points is 120° or more, then the geometric median is the point making that angle. If all the angles are less than 120°, the geometric median is the point inside the triangle which subtends an angle of 120° to each three pairs of triangle vertices. This is also known as the Fermat point of the triangle formed by the three vertices. (If the three points are collinear then the geometric median is the point between the two other points, as is the case with a one-dimensional median.)
• For 4 coplanar points, if one of the four points is inside the triangle formed by the other three points, then the geometric median is that point. Otherwise, the four points form a convex quadrilateral and the geometric median is the crossing point of the diagonals of the quadrilateral. The geometric median of four coplanar points is the same as the unique Radon point of the four points.

## Computation

Despite the geometric median's being an easy-to-understand concept, computing it poses a challenge. The centroid or center of mass, defined similarly to the geometric median as minimizing the sum of the squares of the distances to each point, can be found by a simple formula — its coordinates are the averages of the coordinates of the points — but no such formula is known for the geometric median, and it has been shown that no explicit formula, nor an exact algorithm involving only arithmetic operations and kth roots can exist in general. Therefore only numerical or symbolic approximations to the solution of this problem are possible under this model of computation.[3]

However, it is straightforward to calculate an approximation to the geometric median using an iterative procedure in which each step produces a more accurate approximation. Procedures of this type can be derived from the fact that the sum of distances to the sample points is a convex function, since the distance to each sample point is convex and the sum of convex functions remains convex. Therefore, procedures that decrease the sum of distances at each step cannot get trapped in a local optimum.

One common approach of this type, called Weiszfeld's algorithm after the work of Endre Weiszfeld,[4] is a form of iteratively re-weighted least squares. This algorithm defines a set of weights that are inversely proportional to the distances from the current estimate to the samples, and creates a new estimate that is the weighted average of the samples according to these weights. That is,

$\left. y_{i+1}=\left( \sum_{j=1}^m \frac{x_j}{\| x_j - y_i \|} \right) \right/ \left( \sum_{j=1}^m \frac{1}{\| x_j - y_i \|} \right).$

Bose et al. (2003) describe more sophisticated geometric optimization procedures for finding approximately optimal solutions to this problem. As Nie, Parrilo & Sturmfels (2008) show, the problem can also be represented as a semidefinite program.

## Characterization of the geometric median

If y is distinct from all the given points, xj, then y is the geometric median if and only if it satisfies:

$0 = \sum_{j=1}^m \frac {x_j - y} {\left \| x_j - y \right \|}.$

This is equivalent to:

$\left. y = \left( \sum_{j=1}^m \frac{x_j}{\| x_j - y \|} \right) \right/ \left( \sum_{j=1}^m \frac{1}{\| x_j - y \|} \right),$

which is closely related to Weiszfeld's algorithm.

In general, y is the geometric median if and only if there are vectors uj such that:

$0 = \sum_{j=1}^m u_j$

where for xjy,

$u_j = \frac {x_j - y} {\left \| x_j - y \right \|}$

and for xj = y,

$\| u_j \| \leq 1 .$

An equivalent formulation of this condition is

$\sum _{1\le j\le m, x_j\ne y} \frac {x_j - y} {\left \| x_j - y \right \|} \le \left|\{ \,j\mid 1\le j\le m, x_j= y\,\}\right|.$

## Generalizations

The geometric median can be generalized from Euclidean spaces to general Riemannian manifolds (and even metric spaces) using the same idea which is used to define the Fréchet mean on a Riemannian manifold. Let $M$ be a Riemannian manifold with corresponding distance function $d(\cdot, \cdot)$, let $w_1, \ldots, w_n$ be $n$ weights summing to 1, and let $x_1, \ldots, x_n$ be $n$ observations from $M$. Then we define the weighted geometric median $m$ (or weighted Fréchet median) of the data points as

$m = \underset{x \in M}{\operatorname{arg\,min}} \sum_{i=1}^n w_i d(x,x_i)$.

If all the weights are equal, we say simply that $m$ is the geometric median.

## Notes

1. ^ The more general k-median problem asks for the location of k cluster centers minimizing the sum of distances from each sample point to its nearest center.
2. ^ Lopuhaä and Rousseeuw (1991).
3. ^ Bajaj (1986), Bajaj (1988). Earlier, Cockayne and Melzak (1969) proved that the Steiner point for 5 points in the plane cannot be constructed with ruler and compass
4. ^ Weiszfeld (1937); Kuhn (1973); Chandrasekaran and Tamir (1989).


text:
# Cartesian Product

Let the sets THE = {1, 2, 3} and B = {3, 4}.

With the help of the adjacent arrow diagram, we will form the set of all ordered pairs in which the first element belongs to the set. THE and the 2nd belongs to the set B.

So we get the set: {(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)}

This set is called cartesian product of THE per B, being indicated by:

Soon:

Dice two sets THE and B, nonempty, we call cartesian product THE x B the set of all ordered pairs (x, y) Where

Next: What is a 1st degree equation with two variables?


text:
## Trigonometry 7th Edition

$-\frac{1}{2}$
$\sin(\frac{\pi}{6}-\frac{\pi}{3})$ = $\sin(\frac{-3\pi}{18}) = \sin(-\frac{\pi}{6})$ Using the identity $\sin(-x) = -\sin x$ we obtain, $\sin(-\frac{\pi}{6})$ = $-\sin\frac{\pi}{6}$ = $-\frac{1}{2}$


text:
# Best way for perfect pixel collision detection?

5 replies to this topic

### #1hellhound_01

New Member

• Members
• 58 posts

Posted 31 October 2012 - 11:00 AM

Actually I try to implement a pixel perfect collision (PPC) detection for 2D sprites. For "normal" sprites anything is working perfectly. But how should I handle scaled and rotated sprites?

PPC is expensive, so I try to find an optimized solution to perform PPC. What is the best way I should go? Should I read the actual pixel data from pixel buffer and compare those or should I approximate the scaled values against the origin image data?

Actually I use this approximation attempt to check point based collisions,
but this works not realy good with scaled sprites:

bool brSprite::intersect(float x, float y)
{
// first check if bounding rect collides with point positions
bool collision = this->contains(x, y);

// perform pixel perfect collision if required
if(collision && m_usePPC)
{
/* Substract actual rectangle position from point position value to
reduce intersection point to image dimensions in range: [0,width]
and [0,height].

Please take note that we also have to regard the region x,y
position values to determine correct image position in atlas
textures and a scaling of the sprite.
*/
int pos_x = (int)((x - m_x)+m_region.getX()/m_scale.m_fX);
int pos_y = (int)((y - m_y)+m_region.getY()/m_scale.m_fY);

if(pos_x<m_width && pos_y<m_height){

// define alpha compareable
int alpha = 0;
if(m_ppcTolerance>0){
alpha = (255 * m_ppcTolerance)/100;
}

// perform pixel perfect collision check
brColor color = m_region.getImage()->getPixelColor(pos_x,pos_y);
if(color.getAlpha()>alpha){
collision = true;
}
else{
collision = false;
}
}
}
return collision;
}

Any Ideas?
"There is only one god and his name is death. And there is only one thing we have to say to Death: Not today!" -- Syrio Forel (from Game of Thrones)

### #2Stainless

Member

• Members
• 582 posts
• LocationSouthampton

Posted 31 October 2012 - 12:15 PM

An alternative to pixel perfect collision detection is using collision polygons.

In your editor, you create a polygon that closely fits the image.

It's not perfect, but it's a lot less complex and a lot quicker.

### #3hellhound_01

New Member

• Members
• 58 posts

Posted 31 October 2012 - 12:21 PM

Stainless you are right, this is an option. But I've to use PPC ...
"There is only one god and his name is death. And there is only one thing we have to say to Death: Not today!" -- Syrio Forel (from Game of Thrones)

### #4TheNut

Senior Member

• Moderators
• 1701 posts
• LocationCyberspace

Posted 31 October 2012 - 01:40 PM

In my UI system, I just compute the inverse transformation on the point and check against the image buffer. These checks are being performed every time the cursor position updates, so it's quite frequent and I find the performance impact negligible. Tested on my netbook, it's like a percentage or two of CPU usage with several dozen UI elements on the screen. The benefits of using matrix multiplication is that it covers all grounds (translation, rotation, scale, sheer), and simplifies my code to just an arithmetic operation on the point and inverse transformation matrix. With a UI, demands are much greater because you have to test all objects in front, which can require deep traversals and many tests. With game objects, I would take advantage of spatial partioning to reduce the number of tests. In my particular case, I'm not sure there would be benefits for doing two types of tests. A high level box check and then a low-level pixel check. In both cases, I need to transform the input point, so the hard work has already been done. Performing a point in box check is redundant in my case because my image object already performs boundary checks on accessors. So, naturally I would just request the alpha value at that particular (x,y), do the test, and move on.
http://www.nutty.ca - Being a nut has its advantages.

### #5hellhound_01

New Member

• Members
• 58 posts

Posted 01 November 2012 - 06:09 AM

Hmm, sounds good. Nice idea using object transformation matrix operations.
I've to check this out.
"There is only one god and his name is death. And there is only one thing we have to say to Death: Not today!" -- Syrio Forel (from Game of Thrones)

DevMaster Staff

• Moderators
• 1716 posts

Posted 07 November 2012 - 04:51 PM

Why must you use PPC?

Between PPC and bounding boxes, as Stainless says, you can use more complex geometric shapes. I like techniques that use convex hulls.
Hyperbole is, like, the absolute best, most wonderful thing ever! However, you'd be an idiot to not think dogmatism is always bad.

#### 1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users


text:
# Tag Info

4

When using a Discrete Logarithm based scheme, such as SRP, the rule of thumb is to always use private exponents with a bit length twice the desired security strength. Hence, a 128 bit exponent $a$ will at most give you 64 bits of security. If you want 128 bit security, you need (at least) a 256 bit exponent. This is because the algebraic structure of the ...

3

Solving a 256-bit discrete log is absolutely doable, and quite quickly, these days; there are public tools that can do it, though they may require some expertise to use. On that note, even a 1024-bit modulus is not particularly conservative: it is generally agreed that well-funded organizations today could break logs of that size as well, but at a very ...

3

No, since finding $a$ allows offline checking of passwords. $\:$ No, although I can't back this part up.

2

It seems like a better solution would be to have the server that is providing the Javascript file, also provide a random seed. The Javascript can then use that random seed (and anything other maybe-random bits it can scrounge up, such as the output from Math.random()) to see a cryptographic PRNG, and then use the output of that crypto-PRNG for generating s, ...

2

The purpose is to prevent a two-for-one guessing attack, where an active adversary, impersonating the server, can test two password guesses per attempt. The attack and why the multiplier prevents it is described in Section 2 of the SRP-6 paper (ps). (According to MacKenzie, it was discovered by Bleichenbacher.) In brief, the attack goes like this: Instead ...

2

Being able to solve the discrete logarithm in SRP-6 allows an eavesdropping attacker to dictionary attack the password. It will not directly reveal a strong password or its hash. It requires the attacker to observe a successful authentication, $B$ alone does not suffice. The attacker eavesdrops $s$, $A = g^a$, $B$ and $M_1$. The attacker solves $a$ from ...

2

"Would it be possible for an attacker to launch an offline dictionary/brute-force attack on the B public key: ..." That is possible if and only if the attacker can distinguish b's distribution from the uniform distribution on {0,1,2,3,...,N-3,N-2}. $\:$ If so, an attacker could compute verifiers v for candidate passwords, subtract kv from B mod N, and ...

1

The multiplier parameter $k$ is different between SRP 6 and 6a. You can see that RFC 5054 calculates it using a hash of the domain parameters (modulus $N$ and generator $g$), so it is using SRP 6a, as opposed to SRP 6 where $k$ is constant. Likewise, in section 6.2.1 of IEC 11770-4 – the October 2005 draft at least – the equivalent value $c$ is defined as a ...

1

There is an explicit RCF 5054 which uses SRP to negotiate a shared key for a TLS connection. There are also hooks for OpenSSL to be able to use SRP to setup an SSL connection without using certificates using the SRP generated shared session key.

1

Look at where $a$ is used in the protocol: The user calculates the public $A = g^a$ using it. The user computes the session key as $K = H(S)$, with $S = (B - kg^x) ^ {a + ux}$. An attacker should never find out $S$, because even if the session key $K$ leaks due to e.g. a flawed encryption algorithm, she would only know the hashed value. So knowing or ...

1

You can pre-compute and hardcode N and g into your client and server. There's no harm in doing this. I do not believe that using per-user N will provide any additional security. It is common practice to define SRP parameters for a particular application or (larger) protocol, see e.g. RFC 5054.

Only top voted, non community-wiki answers of a minimum length are eligible


text:
What is a Scalene Triangle? (Definition & Examples) - BYJUS

# Scalene Triangle

In geometry, a triangle is defined as a three-sided closed plane shape with three vertices and three angles. There are various types of triangle but in the following article we will learn about scalene triangles and will understand their properties by some real life examples. ...Read MoreRead Less

## What is a Scalene Triangle?

A triangle in which all three sides are of different lengths and all the three angles of the triangle are also of different measures, is called a scalene triangle.

In comparison an isosceles triangle has two equal sides and an equilateral triangle has three equal sides.

A scalene triangle with three vertices, A, B, and C, is represented as $$\triangle ABC$$

Therefore, it is clear from this image of a scalene triangle that, AB ≠ BC ≠ CA.

## Real-Life Examples of Scalene Triangles

The most common examples of scalene triangles in our daily lives are sailboats, ramps, and roof trusses.

## Properties of Scalene Triangle

1. All the sides of the scalene triangle are unequal.
2. All the angles of the scalene triangle are unequal.
3. As it has no equal sides, hence there is no line of symmetry.
4. It has no point of symmetry.
5. A scalene triangle can be an acute angle, an obtuse angle or a right angle triangle.
6. The formula for the area of a scalene triangle is:

A = $$\sqrt{s~\times~(s-a)~\times~(s-b)~\times~(s-c)}$$

Where, $$s=\frac{a~+~b~+~c}{2}$$

## Solved Scalene Triangle Examples

Example 1: Classify the triangle based on its sides.

Solution:

From the figure, sides of the triangle are 7 cm, 15 cm and 12 cm.

All the sides of the triangle are unequal in length that is

7 ≠ 12 ≠ 15

Hence, it is a scalene triangle.

Example 2: Classify the triangular park according to its sides and then determine the park’s perimeter.

Solution:

From the figure-

Sides of the triangular park are 40 m, 60 m and 90 m

So, all sides of the triangular park are not in the same length.

As a result, it’s a scalene triangle.

To determine its perimeter, find the sum of all the side lengths of the park.

90 + 60 + 40 = 190

Hence, the perimeter of the triangular park is 190  meters.

Example 3: Classify the triangle based on its angles.

Solution:

From the figure, angles of the triangle are 36 degrees, 54 degrees  and 90 degrees.

All the angles of the triangle are not the same.

Hence, it is a scalene triangle.

A triangle with all of its sides are unequal in length is known as a scalene triangle.

As it has no equal sides, there is no line of symmetry in a scalene triangle.

In an equilateral triangle all the three sides are equal in length. However, in a scalene triangle all the three sides are not equal in length.

Based on its sides, a triangle is classified as follows:

1. Equilateral triangle
2. Isosceles triangle
3. Scalene triangle

The perimeter of a scalene triangle is equal to the sum of all of its sides.


text:
I am preparing for the CFA level 2 exam, I got confused by the concept Z-spread and OAS.

When a call option is added to a bond, since it is not favorable to the bond buyer, they would require more spread (which is the OAS) for this instrument in order to get more discount on the bond price.

So to me, Z spread should be less than the OAS.

But this is not what has been discussed in the book. Can someone help with this?

To sum up what is discussed in the CFA curriculum, it discusses 3 types of spreads. They are used to compare a risky bond to a Treasury bond (assumed to be risk-free).

Simply computes the difference between the YTM of the risk-free bond and the YTM of the risky bond.

The major problem of this measure is that it doesn't take into account the shape of the spot yield curve.

This spread is actually a single value that needs to be added to every spot yield of the curve in order to make the present value of the risky bond equal to the present value of the risk-free bond.

That is, if the present value of the risky bond is $v_b$, then the Z-spread $z$ is the value such that:

$$v_b = \sum_{i=1}^N \frac{C}{(1+R_f(0,i)+z)^i}+\frac{FV}{(1+R_f(0,N)+z)^N}$$

where $R_f(0,t)$ is the spot rate for maturity $t$ for a risk-free bond (not annualized).

This still doesn't take into account any embedded option to the risky bond.

This last spread is used to measure the impact of the optionality in the bond. It is defined as follows:

$$\text{OAS}=z-o$$

where $o$ is the the price of the embedded option.

For callable bonds, the option benefits the issuer (it allows him to buy back the bonds if rates go down, i.e. bond prices go up), and $o>0$ hence $\text{OAS}<z$.

For putable bonds, the option benefits the bond owner (it allows him to sell back the bonds if rates go up, i.e. bond prices go down), and $o<0$ hence $\text{OAS}>z$.

It there is no embedded option, then $o=0$, $\text{OAS}=z$.

I believe spreads are to be understood as being used to measure the risk inherent to the core bond, and not to the option that are embedded to it. Hence, if the bond was callable, you required more yield for the bond, but the "core" bond only required a spread equal to the OAS and not really the spread computed by the Z-Spread approach.

• Mathematically, there is an interesting paper related to the non-linearity of this relationship (practically credit spread/o), in "Next Generation Models for Convertible Bonds with Credit Risk", p70, at wilmott.com/pdfs/030813_ayache.pdf Aug 14, 2013 at 12:37
• This is an excellent answer. A bit more detail on OAS – this is typically computed using a term structure model. Assuming the term structure model is implemented using trees or lattices, then OAS is the spread added to each node (i.e., you're shifting each short rate by an amount equal to the OAS) in the tree so that the model price of a securities matches its market price. My favorite report that discusses all these spreads is "Explaining the Lehman Brothers Option Adjusted Spread," which can be found on Google. Jun 1, 2014 at 1:00

The z-spread and OAS both are measures of the difference in price between an ABS and a zero-risk bond. The OAS and z-spread are not spreads that a bond with and without options should require, they are two ways of looking at the same bond.

The CFA material states that the z-spread is equal to the OAS when

1. There is no prepayment option
2. There is a prepayment option, but the borrowers tend not to exercise that option.

The z-spread essentially ignores the option, so a larger spread is needed to explain the price of a bond if there is an option that has a good chance of being exercised.

The Z Spread is the constant spread above the treasury curve that compensates the bond holder for credit, liquidity and option risk.

Thus, the OAS is the spread above the treasury curve that compensates for credit and liquidity risk only.

Z-spread is the all-in spread, meaning spread from the risk profile AND from the call risk. The OAS factors out (subtracts) the additional spread associated with the embedded option, so the OAS will be lower. It's more useful than Z-spread because it allows for apples-to-apples comparisons between bullet maturities & callables. Remember, Z-spread is the spread that, when be added to the discount rate, will equate cash flows to price so this will naturally include spread from all sources, whereas OAS will not include the spread specifically from the option cost.

Sorry for interefering in the discussion as a guest, but I'm studying this topic at the moment for FRM Part II exam, in the context of MBS valuation through Monte Carlo simulation, and at the beginning I had exactly the same doubt. This is the explanation I gave myself and I don't know if it can help:

When you use Z-spread you are not simulating cash flows taking into account the option (in my case, mortgage prepayment by mortgagor), so the resulting sum of the "scheduled" cash flows is higher and, in order to reconcile it with the market price of the security you need, from a purely mathematical point of view, a smaller discount factor (for each time bucket, more precisely), i.e. a higher spread to put in the equation. When, instead, you calculate cash flows using Monte Carlo simulation and take into account interest rate volatility (by means of some assumptions in the model), this means you are considering teh option possibility and this automatically reflects in a smaller value of the scheduled cash flows. This in turn implies that you need a higher discount factor, i.e. a smaller spread, to reconcile this value with the market value of the security.

So I think you should interpret the spread not as what an investor demands, but as what an investor actually earns, over the treasury (or LIBOR, depends on the model) curve by holding the security to maturity. The OAS is smaller because you earn less than holding a security without the embedded option, and this is because the cash flows are actually less.

So the conclusion is that z-spread has to take into account the option risk (so it has to be higher) because this is not taken into account in the structure of the cash flows. Instead, this is not necessary with MT simulation for the reason explained above, i.e. optionality is accounted for in the structure of cash flows and not in the OAS, so in this sense it is an "option adjusted" spread, and I think it more realistically reflects, to an investor, the real value of a security especially if compared with securities without optionality. In this sense we can say, quoting Miles answer above, that OAS "compensates for credit and liquidity risk only", and for this reason this is the spread that should be used if one wants to compare the MBS with, for example, a security (like a traditional bond) that embeds itself only credit and liquidity risk. The presence of the "compensation" for option risk in the z-spread, instead, distorts this commparison and is neither a realistic representation of what the MBS really earns.

Sorry if I've been too verbose, but I hope this clarifies your doubt.

Lots of answers, but I'll throw in something very simple and practical.

Bonds are priced based the spread investors are willing to pay above treasuries. When they determine the price on a bond with optionality, aka the spread, this price is reflected in the Z Spread. The Z Spread is the complete spread required by investors to compensate for all of the risk, including the embedded optionality, of the bond. OAS simply implies, what would the spread on this bond be if there wasn't any optionality as priced in by the market.

eh, just bumped into this. the answer is quite simple - z-spread is based on a curve that is not dynamic. there are different ways to set up your prepayment model, but generally you'd use forward rates. so, for each future period, your prepayment model would use this static curve & a current coupon (index) model to calculate your refinancing incentive and come up with CPR. Once this is done, you have cash flows for each period until your product matures. if a price is already given, what the computer/software will do is calculate the required spread to be added to each point in the static discount spot curve so that the resulting price equals your given price (input).

OAS is a bit more complicated, but in essence you have many (250, for instance) paths, instead of one. so you have 250-sets of cash flows that need to be discounted. depending on how your term structure model is set up, this might affect your valuation (or risk) dramatically. generally, simulating the curve gives you increased prepayments (there is a long answer for this), which drives your cash flows shorter. now these shorter cash flows need to produce the same price, which is given as an input. how do you do that? the simulation discounts less, i.e., adds smaller spread (OAS vs static) to come up with the same final price.

cheers.

d.

What you basically state by OAS = z - o is that OAS is less than the z-spread for callable bonds. Now if you compute the PV of the bond by discounting it by respective yields (Treasury yield + spread) you will find that the the bond discounted using the z-spread will be cheaper than the one discounted by OAS. It does not make sense because as a rational investor I demand a larger discount for the call option that I provide the issuer with.

• You do get a larger discount for the call option. You are mixing up the Z-spread and OAS definitions. Apr 28, 2014 at 0:51

Very insightful discussion. Let me try if I can address this issue. What victor has challenged makes perfect sense, but I think we when calculate z-spread, we just ignore the option. So when we actually calculate call embedded bonds, investors are looking for larger discount to compensate, so the spread is larger which reflect on the market price. And this price is what we use to calculate z-spread. So you will see larger z-spread version put embedded one with smaller z-spread. And Z = OSA + Option. OSA is a ideal spread which is measuring the spread between the fair value and market value. Like if you don't have the call option, the bond price will be higher and the discount rate will be lower, and the spread is smaller. The difference is the price(spread) of option. For call is positive and for put is negative. I hope this can clear some misconceptions.

I think you are just inverting the stuff. (Like I did) You consider Z-spread what, in fact, is OAS.

OAS: discount to add to treasury excluding the option price. (Z-spread of an equivalent bond with no option)

Z-spread: discount to add to treasury for the option bond (thus accounting for the option).

It is misleading because "Option Adjusted" calls for a spread adjusted to reflect the value of the option in the Bond and we instinctively go for it as the actual spread to use for the bond having the option. And, off course, it should reflect a higher discount for a call option, reducing the price of the issue.

They should call it: "Option Excluded Spead" or something like this...

Take care,

Lots of answers, but not totally clear... Let me try to explain the I understood... Take 3 bonds -> 1) treasury bond 2) risky bond 3) risky bond (same as above) with embedded call option

For bond 2, Z-spread = 2% (200 basis points) For bond 3, Z-spread = 3% (which includes the optionality) -> if you adjust the optionality(that is with out option) or OAS, it will be 2% -> which is same as above.

So Z-spread for bond 3 = Z-spread for bond 2(=OAS) + option cost Not sure whether I confused more or make it little clearer.

For an Option Free bond

For a bond with embedded Call options

Option Adjusted Spread + Option Spread = Z spread ( For Callable Bonds) ... Why Option Spread is Positive ? Ans - This is because Investors are to be compensated for additional risk of having callable bonds in their portfolio.

For Bonds with Embedded Put Options

Option Adjusted Spread - Option Spread = Z spread Why option spread is Negative ? - This is because the issuer is to be compensated for the risk of issuing bonds with put option.

So in exam

Z spread > OAS - The bond has an embedded Call option Z spread < OAS - The bond has an embedded Put option Z Spread = OAS - The bond has no embedded options, it is a straight bond

Well many answer here says that Z spread includes option risk. Z spread is zero volatility spread, so at zero volatility option cost is zero that means z spread cannot accommodate a option cost. When valuing a option free risky bond the spread we add to risk-free bond is Z spread. But the same cannot be done when value a risky option embedded bond. First we will have to arrive a riskfree option embedded bond price, which will require volatility assumption and then adjust the value by adding a spread to accommodate riskyness of the bond this spread will be OAS (option adjusted spread)

So after all this if one has to arrive a relation between OAS and Z spread OAS = Z spread +/- option cost depending upon type of option OAS = Z spread - call option OAS = Z spread + put option


text:
# Tag Info

2

Always True In addition to forsvarir's answer, especially the "always True" aspect, I'd like to give an additional reason why to change that. Your parkBigCar() method (and its siblings) is only legal to be called after isPlaceForBigCar() has been checked and returned true. You surely know that today and wrote all your calls appropriately, but if ...

2

this. There's a lot of this. references in your code. Typically in Java you only use this. where you need to in order to disambiguate variables. Consider removing them as they're only adding noise to your code. always True Your park methods all return boolean, even though they all always return true. If you want to maintain the same approach, consider ...

2

I'm not sure if there is enough context for me to fully understand the restrictions you are wporking with but I will try anyway... 25 years ago an elder university student half-jokingly taught me that the solution to any problem is always to "add another layer of indirection." In this case, split handleUpdate so that each message type has their own ...

0

Typically yes, it is a good practice to make MongoClient a singleton. As mentioned in the MongoDB Java driver: The MongoClient instance represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.

1

@Jeremy Hunt's great answer has covered an approach that will make your classes more testable. I'm just going to add a few other things to think about, with your existing code. given..when..then You're naming your tests using a given..when..then approach. If that's your preference, then you may want to consider using Mockito's BDD extensions which might ...

2

You have an iterator Your code implements an iterator, you are right. You have defined a __next__ method and it works well. I would tweak your code slightly, though: remove the check because iterators can be empty and that is okay; fix minor spacing issues around operators, etc; use augmented assignment to increment; change order of statements in __next__ ...

1

Write as little code as possible inside a try I see you are writing some of your code in a EAFP (easier to ask for forgiveness than permission) style, as opposed to a LBYL style (look before you leap). This means that you are using try: ... except: ... blocks, which is perfectly fine and often encouraged in Python (article on EAFP vs LBYL in Python). However,...

1

Short comments as docstrings Docstrings are triple-quoted strings that come immediately after you define a class or function, and they are special in the sense that Python can tell those strings are to be seen as comments that document the code. For most of your methods you have a short comment immediately before the function, which is great. My suggestion ...

2

First lets discuss the class and method naming: StudingClassFirstTime First of all, the word Studing is not in my vocabulary. But please just name classes after what they are supposed to do, and don't include the word class; we know it is a class. load_key: this loads a 32 byte key from file, which is fine, however it doesn't include file in the identifier ...

0

I'd start with defining simple, self-contained things, such as a very generic vector: data class Vector(val x: Int, val y: Int) { companion object { val perpendicular = listOf(Vector(-1, 0), Vector(+1, 0), Vector(0, -1), Vector(0, +1)) val diagonal = listOf(Vector(-1, -1), Vector(+1, +1), Vector(-1, +1), Vector(+1, -1)) val ...

3

The OOP version of the code generated some thoughts around separation of concerns: user interactions and data processing. Single Responsibility Principle(SRP): Every module, class or function in a computer program should have responsibility over a single part of that program's functionality, and it should encapsulate that part. SRP would encourage ...

2

one performance improvement suggestion available_moves Instead of iterating through all the moves create a set with all the moves in the beginning and as each player makes a move remove the corresponding move from the set. In your code both iterating through all moves to find the valid moves(available_moves function) and then the checking if the move given ...

14

This isn’t a bad idea for a learning project, and I’d say it’s implemented quite well. Before I dive into the code itself, I’m going to do a high-level design review. Design review You’re using std::map backwards So you want a list of pairs of values, where one value is the tax rate and the other income lower bound for that tax rate. In your code you made ...

6

In C++ STL, the set and closely related map containers are sorted and provide an efficient way to look up the set element (or map key) which is not less than a given value. This is accomplished using the lower_bound method, which is available for both set and map. You can use this to your advantage here. Instead of having the taxRate map rates to minimum ...

4

There's several parts of your design that can be improved. There is currently lots of duplicate code regarding color, allowed moves, and Pawn1, Pawn2, Pawn3 etc. Is there really any difference between Pawn1, Pawn2, Pawn3, etc? I don't think so. A Piece could be a composition between a player color and an enum class PieceType that lists all the options (...

4

Indents PEP 8: Use 4 spaces per indentation level. Main game loop The way your game loop is set up now is a bit unelegant. You already implemented all the methods to be able to handle both players, there's only one piece missing: from itertools import cycle players = cycle(['X', 'O']) cycle will provide a generator that infinitely repeats the iterable you ...

0

The methods in this class are not really Player methods. They are a combination of game flow, user input and value verification methods. I'd organize it more like this. class Game: def __init__(self): io.show("If ready, let's begin") name = self.get_valid_name() age = self.get_valid_age() self.player = Player(name, age) io....

1

I agree with the advice presented by @slepic. The capacity can be passed as a parameter when a bookshelf is created. The current code treats that capacity as a constant. If you were to keep that capacity as a property that isn’t asssigned vía constructor method, that value could be set when the property is declared, eliminating the need for the constructor: ...

2

Is that really how a bookshelf work? "Hello Magic Bookshelf, report status!" "Bookshelf contain 0 items, remaining capacity is 3" "Ok, spawn a new item!" "0" "Ok give me item 0!" "Here it is, it is The C Programming Language by keringhan & Ritchie" "Got it. Please spawn another item" &...

1

[0-9]{0,} is more simply written as \d* [a-zA-z]{0,} is more simply/accurately written as [a-z]* because you are using a case-insensitive pattern in $pattern later in the script. You may want to validate/sanitize$token before doing $this->api .=$token;. If you are expecting an alphanumeric string, then maybe ctype_alnum(). I don't know the validation ...

3

Style I can not fault the style and layout. The need to call init which is an indirect call to handleClick seams redundant. Do it in the constructor. I am puzzled as to why you set readonly to '' (el.setAttribute('readonly', '');) What has this to do with copying to the clipboard. Names Naming is very poor and also you use inconsistent naming conventions ...

3

In this post I'll focus on the PlayerMovment. Before I try to guide you through the OOP related transformations, let me show you a couple of refactoring techniques which will help you to dramatically reduce the complexity of this method. Guard expression vs Early exit Before private void PlayerMovment() { if (choice2.Checked) { for (...) ...

1

From a short review; Your own answer does read better map is the right approach I would go for filter instead of reduce (you only want 'true' values that are not keyword) I probably would have named total -> keys I prefer <verb><object> so combined -> addGroups If you dont use a falsy comparison, then you dont need to check for 'keyword' ...

0

I have improved it with this: const data = [ { keyword: 'banana', yellow: true, sweet: true }, { keyword: 'pineapple', yellow: true, sweet: false }, { keyword: 'apple', yellow: false, sweet: false }, ] const combined = [...data].map((entry) => { const group = Object.entries(entry).reduce((total, [key,...

3

If this is your first C++ project, then congratulations, it is not a bad attempt at all! However, there are still a lot of areas where your code can be improved. I'll list some of those below. I recommend you try to improve your code based on these suggestions, and the consider creating a new code review question here with the updated code. Don't make ...

2

Disclaimer: I'm currently the maintainer of python-telegram-bot. Hi. TBH I haven't tried to understand every detail of what you presented. I'd still like to comment on the design you chose to use methods of your custom classes as callbacks. More precisely I find it rather irritating that you define methods like class SEMarathonBotSystem: ... @...

1

Typos caled everytime -> called every time MAX_CARACTERS_PER_SEGMENT -> MAX_CHARACTERS_PER_SEGMENT max_caracters -> max_characters And my first language is not French, but shouldn't Votre message dépasse le nombre de {{max_caracters}} caracters be Votre message dépasse le nombre de {{max_characters}} caractères ? Language consistency Your UI is in ...

Top 50 recent answers are included


text:
Poor AI for 2048 written in Haskell

I'm learning Haskell and thought it would be fun to write an AI for the game 2048 in Haskell.

In my implementation I got rid of the randomized aspects of the game.

This makes the program deterministic (or pure). However, I don't think it performs very well. It uses a very simple algorithm:

Recurse into all possible moves with depth x and return the number of empty tiles of the result. The move that results in the highest number of empty tiles is seen as the best move.

I use a 16-length List to represent the board. I am afraid that the many list operations make my program very slow, and wonder if there are better ways to solve this.

The code:

{--

Plays and solves the game 2048

--}
import Data.Time

emptyGrid :: [Int]
emptyGrid = [ 0 | _ <- [0..15] ]

-- Display the 16-length list as the 4 by 4 grid it represents
gridToString :: [Int] -> String
gridToString []         = ""
gridToString xs         = show (take 4 xs) ++ "\n" ++ gridToString (drop 4 xs)

printGrid :: [Int] -> IO()
printGrid xs            = putStrLn $gridToString xs -- Skip n empty tiles before inserting addTile :: Int -> [Int] -> [Int] addTile 0 (0:grid) = 2 : grid addTile n [] = [] addTile n (0:grid) = (0 : addTile (n-1) grid) addTile n (cell:grid) = cell : addTile n grid -- Insert multiple tiles at once addTiles :: [Int] -> [Int] -> [Int] addTiles [] grid = grid addTiles (n:ns) grid = addTiles ns (addTile n grid) -- For one row of the grid, push the non-empty tiles together -- e.g. [0,2,0,2] becomes [2,2,0,0] moveRow :: [Int] -> [Int] moveRow [] = [] moveRow (0:xs) = moveRow xs ++ [0] moveRow (x:xs) = x : moveRow xs -- For one row of the grid, do the merge (cells of same value merge) -- e.g. [2,2,4,4] becomes [4,8,0,0] -- [2,4,2,2] becomes [2,4,4,0] mergeRow :: [Int] -> [Int] mergeRow [] = [] mergeRow (a:[]) = [a] mergeRow (a:b:xs) | a == b = (a + b) : (mergeRow xs) ++ [0] | otherwise = a : mergeRow (b:xs) -- Rotate the grid to be able to do vertical moving/merging -- e.g. [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] -- becomes [0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15] rotate :: [Int] -> [Int] rotate grid = [ grid !! (a + 4 * b) | a <- [0..3], b <- [0..3] ] -- Use the definitions above to do the moves move :: Int -> [Int] -> [Int] move _ [] = [] -- 0=Left, 1=Right, 2=Up, 3=Down move 0 grid = mergeRow (moveRow (take 4 grid)) ++ move 0 (drop 4 grid) move 1 grid = reverse (move 0 (reverse grid)) move 3 grid = rotate (move 0 (rotate grid)) move 2 grid = reverse (move 3 (reverse grid)) -- Mapping of move-codes to text moveToString :: Int -> String moveToString n = ["Left", "Right", "Up", "Down"] !! n -- Take a turn, i.e. make a move and add a tile takeTurn :: Int -> [Int] -> [Int] takeTurn n grid | n == -1 = [] | newGrid /= grid = newGrid | otherwise = [] where newGrid = addTile 0 (move n grid) maxInList :: Ord a => [a] -> a maxInList (x:xs) = maxInList_ x xs maxInList_ :: Ord a => a -> [a] -> a maxInList_ m [] = m maxInList_ m (x:xs) = maxInList_ (max m x) xs -- Find highest tuple in list of pairs. -- On equality, the first wins maxTuple :: [(Int,Int)] -> Int maxTuple [] = -1 maxTuple (x:xs) = secondFromTuple$ maxTuple_ x xs
secondFromTuple :: (a,a) -> a
secondFromTuple (x,y)       = y
maxTuple_ :: Ord a => (a,a) -> [(a,a)] -> (a,a)
maxTuple_ x []              = x
maxTuple_ (a,b) ((y,z):xs)
| a >= y                = maxTuple_ (a,b) xs
| otherwise             = maxTuple_ (y,z) xs

-- Return the best possible move
-- TODO: can the seemingly redundancy be eliminated?
bestMove :: Int -> [Int] -> Int
bestMove depth grid         = maxTuple [ (gridValue depth (takeTurn x grid), x) | x <- [0..2], takeTurn x grid /= [] ]

gridValue :: Int -> [Int] -> Int
gridValue _ [] = -1
gridValue 0 grid = length $filter (==0) grid gridValue depth grid = maxInList [ gridValue (depth-1) (takeTurn x grid) | x <- [0..2] ] -- Take turns and prints the result of each move to the console until no more moves are possible -- n counts the moves -- Should normally be called with n=0 takeTurns :: Int -> Int -> [Int] -> IO() takeTurns depth n grid = do let newGrid = takeTurn (bestMove depth grid) grid if newGrid /= [] then do when (n rem 100 == 0)$ putStrLn $"Move " ++ (show n) -- putStrLn$ "Move " ++ (show n)
-- putStrLn $gridToString newGrid takeTurns depth (n+1) newGrid else do putStrLn$ gridToString grid
putStrLn $"Game Over: " ++ (show n) ++ " Turns" solve :: Int -> IO() solve depth = takeTurns depth 0 emptyGrid solveTenTimes :: Int -> IO() solveTenTimes 10 = putStrLn "Done" solveTenTimes n = do start <- getCurrentTime solve n stop <- getCurrentTime putStrLn$ (show n) ++ ": " ++ (show $diffUTCTime stop start) solveTenTimes (n+1) main = do solveTenTimes 0  Edit I posted a revised version here: Revised: AI for 2048 in Haskell 1 Answer First of all - way to go! Type signatures, pattern matching, monads - you're clearly on the right track. Some general tips: 1. Don't reinvent the wheel! When you encounter a function that looks like this: secondFromTuple :: (a,a) -> a secondFromTuple (x,y) = y  your first thought should be: "wait, that's a really simple and usefuly function. I wonder if it's already in the standard library?". Well, let's search Hoogle for the type signature (a,a)->a: http://www.haskell.org/hoogle/?hoogle=%28a%2Ca%29-%3Ea The first result is: snd :: (a, b) -> b, which is actually the right function. snd is even more general than secondFromTuple - the latter won't work on (0,"zero"), for example, because it's type is (Int,String) and secondFromTuple only work on homogenous tuples. Another example: maximum is a standard library function that behave just like maxInList. Notice that maxInList [] will result in a pattern match failure while maximum [] will result in an empty list exception. Now let's take a look at maxTuple. It takes a list of tuples and return the second item of the tuple with the highest first item. Can we replace it with a standard library function? Well, the Data.List module contains maximumBy :: (a -> a -> Ordering) -> [a] -> a. The By family of functions - sortBy,nubBy - are variation of standard function like maximum,sort and nub, which compares items using an external comparison function. Usually, and easy way to create one is with the comparing function from Data.Ord. For example, comparing fst is a function that gets 2 tuples and compares them by the first element. So maximumBy (comparing fst) will return the tuple with the highest first item, and snd will return its second item. So we can rewrite maxTuple as maxTuple xs = snd$ maximumBy (comparing fst), or in pointfree style - maxTuple = snd . maximumBy (comparing fst).

There's one small issue here: One, we don't know how maximumBy resolves ties - if it's an issue, you can modify the solution a little, maybe use sortBy or write a different comparison function.

2. If you need to fail - fail

maxTuple [] returns -1, and that's not a good idea. maxTuple [(0,-1)] returns -1 as well - how can you tell if it's a valid result?

If a function encounters an invalid state - you need to report an error. There are several ways to do it - I'll mention two:

• Throw an error: maxTuple [] = error "maxTuple: empty list". It's the simplest way to do it, and in a small-scale project it's probably the best. The downside is that error-handling is an IO operation, so this error can't be handled in pure code.

• The Maybe monad:

maxTuple :: [(Int,Int)] -> Maybe Int
maxTuple [] = Nothing
maxTuple xs = Just $snd$ maximumBy (comparing fst)

This is the safer way to do it. A failure results in Nothing. The caller can then deal with this Nothing instead of simply crashing the program. The downside is that now you need to examine the value of maxTuple before using it, which complicates the code. Data.Maybe and Control.Monad can help with this task.

3. Use data instead of hardcoded values

Instead of representing directions with 0-3, you can use data:

data Direction = Left | Right | Up | Down
deriving (Show)

Now move is more readable:

move :: Direction -> [Int] -> [Int]
...
move Left grid  = ...
move Right grid = ...
move Down grid  = ...
move Up grid    = ...

Also, since there's no 5th direction, move 4 results in a pattern match failure. In the new version, there is no such danger.

Plus, deriving (Show) means we can use show on Direction value - so we get moveToString for free: show Left returns "Left", show Down returns "Down" and so on.

That's it for now. Good luck!

• Thanks for your feedback! I'll definately be upgrading my code with your advice. You're right about using library functions... I don't really know my way in the Haskell libraries yet. – wvdz Apr 7 '14 at 23:02
• I implemented your feedback and posted a revised version of my code here: codereview.stackexchange.com/questions/46760/… It would be great if you could take a look at it! – wvdz Apr 9 '14 at 21:59
• Well done! As for the performance issue - have you tried profiling it? GHC has some profiling tools (which I've never used myself) – Benesh Apr 10 '14 at 8:35
• You have a point! – wvdz Nov 3 '14 at 14:39


text:
# [SOLVED] Statistics: Cherry picking data?

1. May 17, 2014

### Nikitin

1. The problem statement, all variables and given/known data
http://www.math.ntnu.no/~haakont/grunnkurs/oppg/eksDes11e.pdf [Broken]
Please take the time to read problem 3 ("Oppgave 3) b, to understand what I am talking about. Everything's explained there.

The specific part I am curious about:

"Define a 90 % confidence interval for $\hat{\beta_1}$. Find the actual result of the interval given the
numbers above.
The company discusses whether the confidence interval could have been shorter if they
instead collected three core samples in both rock types 1 and 3, and only one in rock
type 2? Or what if they took one sample in both of rock types 1 and 3, and five samples

Here they ask if it's a good idea to cherry pick the rock types measured in order to reduce the variance of $\hat{\beta_1}$ (the slope of the regression line), and hence make the confidence interval of $\hat{\beta_1}$ smaller.

2. Relevant equations
$Y_i = \beta_0 + \beta_1 x_i + \epsilon_i$

3. The attempt at a solution

Well, I guess from the math it's quite obvious that $SS_{xx}$ WILL become smaller if you collect samples from primarily rock type 1 and 3, and hence the prediction of the slope becomes more accurate. BUT won't the independence of the error terms condition be hurt by this? Unless they are identically normally distributed regardless of rock type?

And isn't it kind of like cheating?

EDIT: Hmm I think I understand now why this trick works. The bigger $\Delta y$ is between the data points, the less will each data point's random error screw up the accuracy of $\hat{\beta_1}$. OK, I guess I answered my questions after writing everything down on text.

Last edited by a moderator: May 6, 2017
2. May 18, 2014

### Staff: Mentor

Right. It is not cheating if you decide which samples to take in advance (or at least consider "what would have happened if we did that"), and then use all those samples in the analysis.

I hope no company actual uses such a strange model, however - there is absolutely no reason why a linear regression to rock categories should give anything meaningful.


text:
# Thread: Hi I'm new and have a problem with exponential equation.

1. ## Hi I'm new and have a problem with exponential equation.

So I'm a Swede and found this site in an attempt to solve a game problem.

I have a weapon that do 50 dps and damage more per second to a maximum of 200 dps and it maxes out in 45 seconds.

200 - 50 = 150
150 / 45 = 3,33...

So it does 3,33 extra damage per second. Now i want to know how much damage it does after let say 10/s.

50 * 10 + (3,33*10) = 533,33

This sounds wrong since every tick in seconds make it damage more the damage should be closer to.

50 + 3,33
100 + 6,66
150 + 13,33
200 + 26,66
250 + 43,33
300 + 96,66
350 + 183,33
400 + 376,66
450 + 723,33
500 + 1446,66

This way I believe I might get a more accurate number but this is tedious and prone to error since it's done manually and you probably will count something double.

How do i make this calculation with equation?

Side note: If I want to damage lets say 750 and want to know the time until it's reached how do I change the equation to reflect the new wanted output?

2. ## Re: Hi I'm new and have a problem with exponential equation.

I don't know if I understood your problem, but from what I did understand. It looks like an arithmetic progression to me.https://en.wikipedia.org/wiki/Arithmetic_progression

Let $d_t$ be the damage your weapon does in the second t. We know that $d_1=53.33$ and we also know ( from what I understood ) that $d_n=d_{n-1}+3,(33)$. Using this formula $d_{45}=200$ ( I think that $d_n=200$ if n is bigger than 45 ), which seems right. To find how much damage it does after 10s you just need to compute $d_{10}$, which is pretty easy since $d_{10}=53,(33)+9*3,(33)$.

Since your weapon reach a maximum of 200 dps, I assume that you want to know how much seconds will it take to deal a total damge of 750. To find out you need to solve this inequation for k.
$\sum_{t=1}^{k}d_t \geq 750$


text:
# Estimating weight of hidden coin

Consider the following problem:

You have two coins each with it's own weight (probability of giving heads). Somebody will flip the coins for you in another room (you trust them). You can either ask them to flip both coins and they will tell you if they are both heads or not both heads. Or you can ask them to flip only the first coin (you can't only flip the second) and they will tell you if it was heads or not.

How should you proceed to find an estimator of the weight of the second coin. You are allowed to ask the person multiple times. The main goal is to make the estimator not depend on the weight of the first coin. Is this possible?

An aside for motivation of this problem: This is analogous to how measurements in quantum mechanics with linear loss are done. The loss is the first coin, the measurement is the second coin. We can never get rid of the loss but we can do a trivial second measurement (gives always heads) and then the real measurement. Particularly, this is the problem of measuring the polarization degree of freedom of photons from a heralded single photon SPDC source.

• By definition, an estimator cannot depend on the weight of either coin: it can only depend on the results of the flips. It is intuitive that with a very large number of trials you can precisely estimate the "weight" of the first coin. After that your problem is substantially the same as a technique used to ask sensitive survey questions, called "randomized response sampling." This indicates a solution is possible, thereby making the question one of finding an optimal way to estimate the "weight" of the second coin, perhaps by minimizing expected flips using a sequential rule. – whuber May 16 '18 at 19:46
• So to be clear, both coins have unknown weight? – Alex R. May 16 '18 at 22:57
• Yes, both coins have an unknown weight. – Patrick May 17 '18 at 21:33

## 1 Answer

### Method 1: Comparing double and single coin flips as two binomial distributed variables (biased)

Say you flip $n$ times both with $k_n$ times double heads, and you flip $m$ times the first with $k_m$ times the heads. The unknown weights $\theta_1$ and $\theta_2$ can be estimated by the maximum likelihood estimate:

• The conditional probability is $$P(k_n,k_m|\theta_1,\theta_2) = {{n}\choose{k_n}} {{m}\choose{k_m}} \theta_1^{k_n}(1-\theta_1)^{n-k_n} (\theta_1\theta_2)^{k_m}(1-\theta_1\theta_2)^{n-k_m}$$

• Log-likelihood (and eliminating the binomial coefficients): $$\log \mathcal{L}(\theta_1,\theta_2) = k_n \log(\theta_1) + (n-k_n) \log(1-\theta_1)+ k_m \log(\theta_1\theta_2) + (m-k_m) \log (1-\theta_1\theta_2)$$

• Derivatives

$$\frac{\partial\log \mathcal{L}(\theta_1,\theta_2)}{\partial\theta_1} = \frac{k_n}{\theta_1} - \frac{n-k_n}{1-\theta_1} + \frac{k_m}{\theta_1} - \theta_2 \frac{m-k_m}{1-\theta_1\theta_2}$$

$$\frac{\partial\log \mathcal{L}(\theta_1,\theta_2)}{\partial\theta_2} = \frac{k_m}{\theta_2} - \theta_1 \frac{m-k_m}{1-\theta_1\theta_2}$$

• Which is zero for

$$\theta_1 = \frac{k_n}{n}$$ and $$\theta_2 = \frac{k_m}{m} \frac{n}{k_n}$$

This estimate does have some bias. Using simulation I found the expectation value $E(\theta_2)>\theta_2$

(and technically the expectation value is infinite due to the small possibility of $k_n=0$ but you could add some stopping rule that prevents $k_n$ from being zero. Since $k_m < k_n$ anyway I don't believe that this introduces too much bias, if at all)

### Method 2: Performing double coin flips with number of trials depending on the amount of flips necessary to get k heads in single coin flips (unbiased ?)

• You flip the first coin until you got $k$ success and count the number $X$ that you need to flip.

• Then you flip both coins a multiple $n$ times $X$ and count the number $Y$ that both coins land heads.

Intuitively I'd say $\theta_2 = \frac{Y}{nk}$ is an unbiased estimator (with a negative aspect that $\theta_2$ can be above 1). The simulation below seems to show that there is only a small bias (also the variance/error is smaller in comparison to the first method with similar amount of coin flips). You would have to compute the conjugate distribution for the variable $Y$ to see if there is no bias.

k=50
p1=0.5
p2=0.5
n=10
X <- rnbinom(10000,k,p1)+k
Y <- rbinom(10000,X*n,p1*p2)
mean(Y/k/n-p2)
var(Y/k/n)
plot(hist(Y/k/n))


text:
## Applied Statistics Lesson of the Day – Polynomial Regression is Actually Just Linear Regression

Continuing from my previous Statistics Lesson of the Day on what “linear” really means in “linear regression”, I want to highlight a common example involving this nomenclature that can mislead non-statisticians.  Polynomial regression is a commonly used multiple regression technique; it models the systematic component of the regression model as a $p\text{th}$-order polynomial relationship between the response variable $Y$ and the explanatory variable $x$.

$Y = \beta_0 + \beta_1 x + \beta_2 x^2 + ... + \beta_p x^p + \varepsilon$

However, this model is still a linear regression model, because the response variable is still a linear combination of the regression coefficients.  The regression coefficients would still be estimated using linear algebra through the method of least squares.

Remember: the “linear” in linear regression refers to the linearity between the response variable and the regression coefficients, NOT between the response variable and the explanatory variable(s).

## Machine Learning Lesson of the Day – Estimating Coefficients in Linear Gaussian Basis Function Models

Recently, I introduced linear Gaussian basis function models as a suitable modelling technique for supervised learning problems that involve non-linear relationships between the target and the predictors.  Recall that linear basis function models are generalizations of linear regression that regress the target on functions of the predictors, rather than the predictors themselves.  In linear regression, the coefficients are estimated by the method of least squares.  Thus, it is natural that the estimation of the coefficients in linear Gaussian basis function models is an extension of the method of least squares.

The linear Gaussian basis function model is

$Y = \Phi \beta + \varepsilon$,

where $\Phi_{ij} = \phi_j (x_i)$.  In other words, $\Phi$ is the design matrix, and the element in row $i$ and column $j$ of this design matrix is the $i\text{th}$ predictor being evaluated in the $j\text{th}$ basis function.  (In this case, there is 1 predictor per datum.)

Applying the method of least squares, the coefficient vector, $\beta$, can be estimated by

$\hat{\beta} = (\Phi^{T} \Phi)^{-1} \Phi^{T} Y$.

Note that this looks like the least-squares estimator for the coefficient vector in linear regression, except that the design matrix is not $X$, but $\Phi$.

If you are not familiar with how $\hat{\beta}$ was obtained, I encourage you to review least-squares estimation and the derivation of the estimator of the coefficient vector in linear regression.

## How to Calculate a Partial Correlation Coefficient in R: An Example with Oxidizing Ammonia to Make Nitric Acid

#### Introduction

Today, I will talk about the math behind calculating partial correlation and illustrate the computation in R.  The computation uses an example involving the oxidation of ammonia to make nitric acid, and this example comes from a built-in data set in R called stackloss.

I read Pages 234-237 in Section 6.6 of “Discovering Statistics Using R” by Andy Field, Jeremy Miles, and Zoe Field to learn about partial correlation.  They used a data set called “Exam Anxiety.dat” available from their companion web site (look under “6 Correlation”) to illustrate this concept; they calculated the partial correlation coefficient between exam anxiety and revision time while controlling for exam score.  As I discuss further below, the plot between the 2 above residuals helps to illustrate the calculation of partial correlation coefficients.  This plot makes intuitive sense; if you take more time to study for an exam, you tend to have less exam anxiety, so there is a negative correlation between revision time and exam anxiety.

They used a function called pcor() in a package called “ggm”; however, I suspect that this package is no longer working properly, because it depends on a deprecated package called “RBGL” (i.e. “RBGL” is no longer available in CRAN).  See this discussion thread for further information.  Thus, I wrote my own R function to illustrate partial correlation.

Partial correlation is the correlation between 2 random variables while holding other variables constant.  To calculate the partial correlation between X and Y while holding Z constant (or controlling for the effect of Z, or averaging out Z),

## Presentation Slides – Overcoming Multicollinearity and Overfitting with Partial Least Squares Regression in JMP and SAS

My slides on partial least squares regression at the Toronto Area SAS Society (TASS) meeting on September 14, 2012, can be found here.

#### My Presentation on Partial Least Squares Regression

My first presentation to Toronto Area SAS Society (TASS) was delivered on September 14, 2012.  I introduced a supervised learning/predictive modelling technique called partial least squares (PLS) regression; I showed how normal linear least squares regression is often problematic when used with big data because of multicollinearity and overfitting, explained how partial least squares regression overcomes these limitations, and illustrated how to implement it in SAS and JMP.  I also highlighted the variable importance for projection (VIP) score that can be used to conduct variable selection with PLS regression; in particular, I documented its effectiveness as a technique for variable selection by comparing some key journal articles on this issue in academic literature.

The green line is an overfitted classifier.  Not only does it model the underlying trend, but it also models the noise (the random variation) at the boundary.  It separates the blue and the red dots perfectly for this data set, but it will classify very poorly on a new data set from the same population.


text:
# Trouble finding what this recurrence solves to [duplicate]

I have a recurrence relation of the form $$T(n) = 2T(n/2)+O(1)$$

I'm not sure how to deal with the big $$O$$-notation in the problem in order to start solving it ? Any help would be appreciated.

## marked as duplicate by Yuval Filmus, ryan, Evil, Juho, xskxzrMay 26 at 2:09

Hint: can you solve it for $$n = 2^k$$ where we replace $$O(1)$$ with constant $$c$$ and let $$f(1) = c$$? Then you have:
$$f(2^k) = 2f(2^{k-1}) + c$$
Then the pattern starts $$f(1) = c$$, $$f(2) = 3c$$, $$f(4) = 7c$$, $$f(8) = 15c$$... any guesses?


text:
# Commutative algebras¶

class sage.categories.commutative_algebras.CommutativeAlgebras(base, name=None)

The category of commutative algebras with unit over a given base ring.

EXAMPLES:

sage: M = CommutativeAlgebras(GF(19))
sage: M
Category of commutative algebras over Finite Field of size 19

TESTS:

sage: TestSuite(CommutativeAlgebras(ZZ)).run()

Todo:

• product ( = cartesian product)
• coproduct ( = tensor product over base ring)
super_categories()

EXAMPLES:

sage: CommutativeAlgebras(QQ).super_categories()
[Category of algebras over Rational Field, Category of commutative rings]

#### Previous topic

Commutative algebra ideals

#### Next topic

Commutative ring ideals


text:
# Tuesday Update

## If you weren’t sick of Theranos yet….

Looks like there will be a movie version of the Theranos saga which, as far as I can tell, isn’t over yet, but no matter. It will be done by Adam McKay, the writer-director of The Big Short (excellent film), and will star Jennifer Lawrence as Elizabeth Holmes. From Vanity Fair:

Legendary Pictures snapped up rights to the hot-button biopic for a reported $3 million Thursday evening, after outbidding and outlasting a swarm of competition from Warner Bros., Twentieth Century Fox, STX Entertainment, Regency Enterprises, Cross Creek, Amazon Studios, AG Capital, the Weinstein Company, and, in the penultimate stretch, Paramount, among other studio suitors. Based on a book proposal by two-time Pulitzer Prize-winning journalist John Carreyrou titled Bad Blood: Secrets and Lies in Silicon Valley, the project (reported to be in the$40 million to \$50 million budget range) has made the rounds to almost every studio in town. It’s been personally pitched by McKay, who won an Oscar for best adapted screenplay for last year’s rollicking financial meltdown procedural The Big Short.

Frankly, I think we all know how this movie will end.

## The People vs. OJ Simpson vs….Statistics

I’m in the middle of watching The People vs. OJ Simpson and so far it is fantastic—I highly recommend it. One thing that is not represented in the show is the important role that statistics played in the trial. The trial was just in the early days of using DNA as evidence in criminal trials and there were many questions about how likely it was to find DNA matches in blood.

Terry Speed ended up testifying for the defense (Simpson) and in this nice interview, he explains how that came to be:

At the beginning of the Simpson trial, there was going to be a pre-trial hearing and experts from both sides would argue in front of the judge as to what approaches should be accepted. Other pre-trial activities dragged on, and the one on DNA forensics was eventually scrapped. The DNA experts, including me were then asked whether they wanted to give evidence for the prosecution or defence, or leave. I did not initially plan to join the defence team, but wished to express my point of view in what was more or less a scientific environment before the trial started, but when the pre-trial DNA hearing was scrapped, I decided that I had no choice but to express my views in court on behalf of the defence, which I did.

The full interview is well worth the read.

## AI is the residual

I just recently found out about the AI effect which I thought was interesting. Basically, “AI” is whatever can’t be explained, or in other words, the residuals of machine learning.

# A Year at Stack Overflow

David Robinson (@drob) has a great post on his blog about his first year as a data scientist at Stack Overflow. This section in particular stood out for me:

I like using R to learn interesting things about our data, but my longer term goal is to make it easy for any of our engineers to do so….Towards this goal, I’ve been focusing on building reliable tools and frameworks that people can apply to a variety of problems, rather than “one-off” analysis scripts. (There’s an awesome post by Jeff Magnusson at StitchFix about some of these general challenges). My approach has been building internal R packages, similar to AirBnb’s strategy (though our data team is quite a bit younger and smaller than theirs). These internal packages can query databases and parsing our internal APIs, including making various security and infrastructure issues invisible to the user.

The world needs an army of David Robinsons.

# Ultimate AI battle - Apple vs. Google

Yesterday, Apple launched its Worldwide Developer’s Conference (WWDC) and had its public keynote address. While many new things were announced, the one thing that caught my eye was the dramatic expansion of Apple’s use of artificial intelligence (AI) tools. I talked a bit about AI with Hilary Parker on the latest Not So Standard Deviations, particularly in the context of Amazon’s Echo/Alexa, and I think it’s definitely going to be an area of intense competition between the major tech companies.

Pretty much every major tech player is involved in AI—Google, Facebook, Amazon, Apple, Microsoft—the list goes on. Recently, a some commentators have suggested that Apple in particular will never catch up with the likes of Google with respect to AI because of Apple’s strict stance on privacy and unwillingness to gather/aggregate data from all its users. However, yesterday at WWDC, Apple revealed a few clues about what it was up to in the AI world.

First, Apple mentioned deep learning more than a few times, including specifically calling out its use of LSTM in its Messages app and facial recognition in its Photos app. Previously, Apple had been rumored to be applying deep learning to its Siri assistant and its fingerprint sensor. At WWDC, Craig Federighi stressed Apple’s continued focus on privacy and how Apple does not need to develop “user profiles” server-side, but rather does most computation on-device (in this case, on the iPhone).

However, it can’t be that Apple does all its deep learning computation on the iPhone. These models tend to be enormous and take advantage of reams of data that can only be reasonablly processed server-side. Unfortunately, because most companies (Apple in particular) release few details about what they do, we may never how this works. But we can definitely speculate!

I think the Apple/Google dichotomy provides an interesting opportunity to talk about how models can be learned using data in different ways. There are two approaches being represented here by Apple and Google:

• Google way - Collect lots of data from users and store them on a server in the Googleplex somewhere. Then use that data to fit an enormous model that can predict when you’ve taken a picture of a cat. As users generate more data, bring that data back to the Googleplex and update/refine the model.
• Apple way - Build a “starter model” in the Apple Mothership. As users generate data on their phones, bring the model to the phone and update the model using just their data. Bring the updated model back to the Apple Mothership and leave the user’s data on the phone.

Perhaps the easiest way to understand this difference is with the arithmetic mean, which is perhaps the simplest “model”. Suppose you have a bunch of users out there and you want to compute the average of some attribute that they have on their phones (or whatever device). The first approach would be to get all that data and compute the mean in the usual way.

Once all the data is in the Googleplex, we can just use the formula

I’ll call this the “Google mean” because it requires that you get all the data X1 through Xn, then sum them up and divide by n. Here, each of the Xi’s represents the ith user’s data. The general principle here is to gather all the data and then estimate the model parameters server-side.

What if you didn’t want to gather everyone’s data centrally? Can you still compute the mean?

Yes, because there’s a nice recurrence formula for the mean:

We can call this the “Apple mean”. With this strategy, we can send our current estimate of the mean to each user, update our estimate by taking the weighted average of the old value and the new value, and then move on to the next user. Here, you send the model parameters out to the users, update those parameters and then bring the parameters back.

Which method is better? Well, in this case, both give you the same answer. In general, for linear models (like the mean), you can usually rework the formulas to build out either “whole data” (Google) approaches or “streaming” (Apple) approaches and get pretty much the same answer. But for non-linear models, it’s not so simple and you usually cannot achieve this kind of equivalence.

## Clients and Servers

Balancing how much work is done on a server and how much is done on the client is an age-old computing problem and, over time, the balance of work between client and server seems to shift back and forth like a pendulum. When I was in grad school, we had so-called “dumb terminals” that were basically a screen that you used to login to the server. Today, I use my laptop for computing/work and that’s it. But I use the cloud for many other tasks.

The Apple approach definitely requires a “fatter” client because the work of integrating current model parameters with new user data has to happen on the phone. With the Google approach, all the phone has to do is be able to collect the data and send it over the network to Google.

The Apple approach is also closely related to what my colleagues Martin Lindquist and Brian Caffo refer to as “fusion science”, whereby Big Data and “Small Data” can be fused together via models to improve inference, but without ever having to actually combine the data. In a Bayesian context, you might think of the Big Data as making up the prior distribution and the Small Data as the likelihood. The Small Data can be used to update the model parameters and produce the posterior distribution, after which the Small Data can be thrown out.

## And the Winner is…

It’s not clear to me which approach is better in terms of building a better model for prediction or inference. Sadly, we may never have enough details to find out, and will only be ablle to evaluate which approach is better by the performance of the systems in the marketplace. But perhaps that’s the way things should be evaluated in this case?

# Good list of good books

The MultiThreaded blog over at Stitch Fix (hat tip to Hilary Parker) has posted a really nice list of data science books (disclosure: one of my books is on the list).

We’ve queried our data science team for some of their favorite data science books. This list is by no means exhaustive, but should keep any data scientist/engineer new or old learning and entertained for many an evening.

Enjoy!

# Not So Standard Deviations Episode 17 - Diurnal High Variance

Hilary and I talk about Amazon Echo and Alexa as AI as a service, the COMPAS algorithm, criminal justice forecasts, and whether algorithms can introduce or remove bias (or both).

If you have questions you’d like us to answer, you can send them to nssdeviations @ gmail.com or tweet us at @NSSDeviations.

Please leave us a review on iTunes!

Support us through our Patreon page.

Show notes:


text:
## Research vs implementation, theory vs practice, and LtU

There's a conflict between doing research and creating usable programming languages, and different people have different interests.
However, some LtU regulars seem to believe (some variation of) PL research is somehow pointless. (I won't try to offer an exact summary, it's too hard, so this might well be a strawman).

Instead of discussing this inside other topic, it seems this topic deserves its own thread, because the question is interesting. I'm not sure there's something new to say on the topic — this is an old discussion. And I guess that some of us will still not be personally interested in research. But I'd like to not hear the wrong arguments against research. I don't want to hear that research will never be useful in practice. I'm fine with hearing, say, that if you want something now, theoretical research is often not what you should look into — theoretical researchers figure out what you should use in a few years or decades.

## Comment viewing options

### Types are Actors that can be used in computations

Of course, types are Actors that can be used in computations just like other Actors.

But parametrized types require special treatment and rules.

### Types are Actors In ActorScript

I think you mean to say that types are actors in ActorScript. There are many type systems where types are simple types, and values are values, and there are no actors at all.

### Dependent types not needed

Some of the above are possible even without dependent types. For example, Rossberg's 1ml unifies functions and functors (type constructors) and allows you to treat list as a value of type type -> type, while desugaring into plain System Fω (heavily utilizing existential quantifiers and higher-kinded types).

As for types like array[float, 3], I'd prefer something like refined types with an automatic theorem prover instead of full-blown dependent types.

### Lack of positive feedback

Much has been written about the downsides of gamification, but at least it does add some positive feedback to a discussion. Many of those empty conversations could be:
* Yes, that is very interesting but personally I have no comment to make.
* That's a load of rubbish, I have no interest in that at all.
* I like what is being said but I agree with the viewpoint being expressed so there is no way to join in without a somewhat empty "me too!" +1.
Where, currently there is no real way to tell these states apart.

I agree completely with your observations on the literature at large, and the underlying causes for its current state. I also really like reading the contributions that gasche makes, although frequently I fall into one of two of the states above, and thus don't really add anything.

What kind of mechanism (social or technical) would add some positive feedback to the discussions on LtU without falling into the trap of reinforcing groupthink / gamifying the site?

### The context of a discussion

The context of a discussion can make all the difference in how developable it is. The first mention of my fexpr research on LtU (that I know of), a straightforward sharing of the Kernel web page I was maintaining, didn't generate much discussion (though it did result in my becoming aware of, and ultimately joining, LtU :-). From time to time fexprs/Kernel were relevant to discussions and I'd make small comments when they seemed pertinent; but the deep, interesting discussion of the issues involved that I'd have liked to have didn't occur until about three and a half years later, with a topic on first-class environments. So, patience and looking at things from different angles can eventually pay off.

[Note, I'm looking just at what it took for that particular theme to get discussed in depth.]

### Silent is fine

To clarify, I think that having no comment to make is perfectly fine (whether one is interested in the work or not), and I am not particularly troubled by the fact that most discussions are very quiet for this likely reason. Having stimulating discussions of the presented work is always great, but we should not expect it to be the default state.

(We could also afford a lot more of "I don't know about X and thus don't understand point Y, can anyone provide extra details?" comments than we have today.)

### Absolutely.

… and while I personally could benefit in a few cases from the "don't understand" point, I would consider it a shame if LtU became a PL version of stack exchange.

LtU is intimidating at first, and although that may dissuade the casual browser, it's what makes the place unique. For non-academic members (and possibly for those in academia) it's necessary to read the papers (in my case, sometimes multiple times) to even begin to get a grasp of what's going on, and that's far too much like hard work for the majority of “internautes”. I often find myself thinking "I'm way out of my league here", but try and follow along anyway - the voyage can be as interesting as the final destination.

### metaprogramming

I think I forgot it from my laundry list, and it's important to me.

I read an argument the other day that made me rethink, somewhat my objection to simplified languages like types.

It was related to "The Principle of Least Power" - a suggestion that it's good programming practice to code in the least powerful language that expresses the problem.

The part I found myself nodding to was the idea that if the description of the program is simple enough, then you can process it automatically, change it, implement it in different ways. The was a suggestion that powerful and expressive languages are brittle to code-transformation.

It's an argument, I think, not for limited languages so much as for domain specific languages, and for metaprogramming facilities.

The most common example of this might be XML used for user interfaces.

But in most systems, types are there for static analysis, so they're not first class objects and they're not a DSL. So I'm still not really talking about types.

### Research and PL

I think the question is well intended, but it's the kind of question that produces a lot of opinionated but uninformed discussion. Even, to some degree, here on LtU.

The first point I want to make, which has been made here already, is that many successful new programming languages - perhaps most - originate from research. C, C++, Java, Basic, Pascal (and yes, that was successful), Objective-C, Smalltalk (and yes, in some domains that was very successful too), Prolog (also successful in some domains), C#, F#, Python, Scala, Lua, Erlang, to name just a few. BitC too, if that ultimately turns out to have uptake. It's hard to make broad judgments without a comprehensive list of languages in front of me.

Subjectively, it has seemed to me that languages designed outside of research have tended to be more ad hoc, and have often suffered from their ad hoc nature. Swift, Rust, Perl, and D come to mind. In some cases the industry collectively has spent very large sums for the consequences of using these languages. This is not universally true. SQL stands out as an industrially originated language, though it built heavily on research antecedents.

I think the focus on Lambda calculus in the original question is a bit off. Coherent languages need some clearly defined semantics. Lambda calculus has been the most mature and best understood, thus the emphasis, but it isn't the only one. Pi calculus is a fine alternative, and may be better suited for OO languages. Lambda calculus per se is an academic construct, but the value of knowing what a program means is not limited to purely academic pursuits. Rigor has value in industry too. BitC cannot be captured by the traditional typed lambda calculus (because of self type for objects), but it clearly needs a rigorous and formally captured semantics.

Again subjectively, it has seemed to me that over the last decade there has been a striking trend in favor of new languages being more rigorous (Swift a notable exception). That seems all to the good.

Finally, I think the line between researcher and industrial practitioner is a false dichotomy more often than people realize. Which side of that line do I fall on? Which side does Guy Steele fall on? How about Don Syme?

### It would be hard to call C#

It would be hard to call C# an acedemic language, or , for that matter, C++, F#. They came from companies, often involved some non PhDs, and anyways, were driven in solving problems vs. investigations of the possible. Are bell labs, Microsoft research, Xerox park like universities with acedemic research projects? Not really. Is Anders an acedemic trying to publish papers or an experienced language designer? The answer to that is easy. Was Don Syme doing research when he designed F#, or was he designing a language to fill a need?

Also, foundationally speaking, you don't need clearly defined semantics at the onset, and plenty of languages are used successfully without them. That is not to say they aren't useful, but necessary is a much higher bar! Of course, when we start talking about Rust and BitC that are claiming some extra degree of safety, then it is kind of a different ballgame. But there also has to be value in those semantics, they have to pay off or it is just cargo culting tedium. E.g. What would Swift gain from more formal work? Beyond full employment for PL researchers, what is in it for programmers? Why not invest it better tooling instead?

The rigor fad seems to have started when GLS was put on to do the JLS along with Gilad Bracha. But as far as I can tell, only C# (out of the production languages) has gotten similar attention given work from people in MSR (along with Mads). No one else really has the resources for it, and even Scala lacks much in terms of formal specification. So swift is not really an exception at all, rather it is the same process that new languages start and get big have always followed.

### ad hoc-ness and shoulders of giants

I'll question that "usable" is equivalent to "has lots of users", and I'll question that "research" is a value in itself.

Let's go for "lots of users": With the right budget, it might be quite easy to get lots of users: use only tried and tested ideas, keep everything as simple as possible, write documentation, maintain backwards compatibility, practice some form of marketing, hire people to write GUI libraries, run on lots of platforms, provide acceptable performance, fill a gap...

You can see how this recipe over time leads to languages that become less and less usable: as usage increases, new gaps are identified and revisions become necessary... I think it might be rational for a company to evaluate the results of research activity in economical terms, and that will lead to decisions that may or may not be pleasing to researchers and likewise such evaluation may have been too shortsighted and thus important developments are missed or picked up too late by "the" industry.

The whole discussion here is bound to be rendered a bit more obsolete (or imprecise) by the next appearance of some research output in an "applied" language, or the next research paper that solves a problem that was only found in "industry" language X.

There are programmers (and programming situations) where a spec will be preferable to all sorts of tooling, and then there are tools that will make inherent language shortcomings bearable. There is also a lot to be said about free and open source software and how it builds a body of research that one probably would not call academic but it contributes to the body of human knowledge in a very similar way.

### GLS, JLS, MSR

Too many acronyms. Needs lowercase.

### Guy L. Steele, Java language

Guy L. Steele, Java language specification, Microsoft research.

Great. Thanks.

### Typing on tablets leads to

Typing on tablets leads to shortcuts.

Yeah, I've seen you do it more often. It makes your posts hard to read sometimes, though.

### It's summer and China lacks

It's summer and China lacks daylight savings time, I wake up at 4am in the morning and have nothing to do but post to LtU from bed using an iPad.

### Homoiconic languages

I have an interest in this.

Mathematica is cool, but I want one that isn't limited to symbolic processing on mathematical expressions, I want other DSLs and meta programming.

I'm familiar with Prolog (which I think is homoiconic in a better way than Lisp and Scheme), but there's a bunch of programming languages I haven't got to yet. REBOL and its open sourced variants and io and maybe pure?