**Design of Temporary and Permanent Joints**

A bracket supports a load of 30 kN. Determine the size of bolts, given the maximum allowable tensile stress in the bolt material is 60 MPa. The distances are: L1 = 80 mm, L2 = 250 mm, and L = 500 mm.

Given: W = 30 kN, σt = 60 MPa, L1 = 80 mm, L2 = 250 mm, L = 500 mm.

We know that the direct tensile load carried by each bolt, Wt1 = (W / n) = 30 / 4 = 7.5 kN. Load in a bolt per unit distance, = WL / 2[(L1)^{2} + (L2)^{2}] = 30 x 500 / 2[80^{2} + 250^{2}] = 0.109 kN/mm.

Since the heavily loaded bolt is at a distance of L2 mm from the tilting edge, therefore load on the heavily loaded bolt, Wt2 = w.L2 = 0.109 × 250 = 27.25 kN. Maximum tensile load on the heavily loaded bolt, Wt = Wt1 + Wt2 = 7.5 + 27.25 = 34.75 kN = 34750 N.

Let dc = Core diameter of the bolts. We know that the maximum tensile load on the bolt (Wt), 34750 = (π / 4) × (dc)^{2} σt. (dc)^{2} = 34750 / 47 = 740, dc = 27.2 mm.

From Table 11.1 (coarse series), we find that the standard core diameter of the bolt is 28.706 mm and the corresponding size of the bolt is M 33.

**Design a sleeve and cotter joint** to resist a tensile load of 60 kN. All parts of the joint are made of the same material with the following allowable stresses: σt = 60 MPa, τ = 70 MPa, and σc = 125 MPa.

Given: σc = 125 MPa, σt = 60 MPa, τ = 70 MPa, P = 60 kN.

1. Diameter of the rods: Let d = Diameter of the rods. Considering the failure of the rods in tension, we know that load (P), 60 × 10^{3} = (π/4) × d^{2} × σt. d^{2} = 60 × 10^{3} / 47.13 = 1273, d = 35.7 say 36 mm.

2. Diameter of enlarged end of rod and thickness of cotter: Let d2 = Diameter of enlarged end of rod, and t = Thickness of cotter. It may be taken as d2 / 4. Considering the failure of the rod in tension across the weakest section (i.e., slot), we know that load (P), 60 × 10^{3} = [(π/4) (d2)^{2} - (π/4) d^{2}] σt. (d2)^{2} = 60 × 10^{3} / 32.13 = 1867, d2 = 43.2 say 44 mm. Thickness of cotter, t = (d2/4) = 44/4 = 11 mm.

Let us now check the induced crushing stress in the rod or cotter. We know that load (P), 60 × 10^{3} = d2 × t × σc. 60 × 10^{3} = 44 × 11 × σc, σc = 60 × 10^{3} / 484 = 124 N/mm^{2}. Since the induced crushing stress is less than the given value of 125 N/mm^{2}, therefore the dimensions d2 and t are within safe limits.

3. Outside diameter of sleeve: Let d1 = Outside diameter of sleeve. Considering the failure of sleeve in tension across the slot, we know that load (P), 60 × 10^{3} = (d1 - d2) t × σt. 60 × 10^{3} = (d1 - 44) 11 × 60, d1 = 58.4 say 60 mm.

4. Width of cotter: Let b = Width of cotter. Considering the failure of cotter in shear, since the cotter is in double shear, therefore load (P), 60 × 10^{3} = 2 × b × t × τ. 60 × 10^{3} = 2 × b × 11 × 70, b = 38.96 say 40 mm.

Distance of the rod from the beginning to the cotter hole (inside the sleeve end): Let a = Required distance. Considering the failure of the rod end in shear, since the rod end is in double shear, therefore load (P), 60 × 10^{3} = 2 × a × d2 × τ. 60 × 10^{3} = 2 × a × 44 × 70, a = 9.74 say 10 mm.

Distance of the rod end from its end to the cotter hole: Let c = Required distance. Considering the failure of the sleeve end in shear, since the sleeve end is in double shear, therefore load (P), 60 × 10^{3} = 2 × (d1 - d2) × c × τ. 60 × 10^{3} = 2 × (60 - 44) × c × 70, c = 26.78 say 28 mm.

**Design a knuckle joint** to transmit 150 kN. The design stresses may be taken as 75 MPa in tension, 60 MPa in shear, and 150 MPa in compression.

Given: P = 150 kN, σt = 75 MPa, τ = 60 MPa, σc = 150 MPa.

The knuckle joint is shown in Fig. 12.16. The joint is designed by considering the various methods of failure as discussed below:

1. Failure of the solid rod in tension: Let d = Diameter of the rod. We know that the load transmitted (P), 150 × 10^{3} = (π/4) × d^{2} × σt. d^{2} = 150 × 10^{3} / 59 = 2540, d = 50.4 say 52 mm.

Now the various dimensions are fixed as follows: Diameter of knuckle pin, d1 = d = 52 mm. Outer diameter of eye, d2 = 2d = 2 × 52 = 104 mm. Diameter of knuckle pin head and collar, d3 = 1.5d = 1.5 × 52 = 78 mm. Thickness of single eye or rod end, t = 1.25d = 1.25 × 52 = 65 mm. Thickness of fork, t1 = 0.75d = 0.75 × 52 = 39 say 40 mm. Thickness of pin head, t2 = 0.5d = 0.5 × 52 = 26 mm.

2. Failure of the knuckle pin in shear: Since the knuckle pin is in double shear, therefore load (P), 150 × 10^{3} = 2 × (π/4) × d1^{2} × τ. 150 × 10^{3} = 2 × (π/4) × 52^{2} × τ, τ = 150 × 10^{3} / 4248 = 35.3 N/mm^{2} = 35.3 MPa.

Failure of the single eye or rod end in tension: The single eye or rod end may fail in tension due to the load. We know that load (P), 150 × 10^{3} = (d2 - d1) × t × σt. 150 × 10^{3} = (104 - 52) × 65 × σt, σt = 150 × 10^{3} / 3380 = 44.4 N/mm^{2} = 44.4 MPa.

Failure of the single eye or rod end in shearing: The single eye or rod end may fail in shearing due to the load. We know that load (P), 150 × 10^{3} = (d2 - d1) × t × τ. 150 × 10^{3} = (104 - 52) × 65 × τ, τ = 150 × 10^{3} / 3380 = 44.4 N/mm^{2} = 44.4 MPa.

Failure of the single eye or rod end in crushing: The single eye or rod end may fail in crushing due to the load. We know that load (P), 150 × 10^{3} = d1 × t × σc. 150 × 10^{3} = 52 × 65 × σc, σc = 150 × 10^{3} / 3380 = 44.4 N/mm^{2} = 44.4 MPa.

Failure of the forked end in tension: The forked end may fail in tension due to the load. We know that load (P), 150 × 10^{3} = (d2 - d1) × 2 × t1 × σt. 150 × 10^{3} = (104 - 52) × 2 × 40 × σt, σt = 150 × 10^{3} / 4160 = 36 N/mm^{2} = 36 MPa.

Failure of the forked end in shear: The forked end may fail in shearing due to the load. We know that load (P), 150 × 10^{3} = d1 × t × σc. 150 × 10^{3} = 52 × 65 × σc, σc = 150 × 10^{3} / 3380 = 44.4 N/mm^{2} = 44.4 MPa.

Failure of the forked end in crushing: The forked end may fail in crushing due to the load. We know that load (P), 150 × 10^{3} = d1 × 2 × t1 × σc. 150 × 10^{3} = 52 × 2 × 40 × σc, σc = 150 × 10^{3} / 4180 = 36 N/mm^{2} = 36 MPa.

From above, we see that the induced stresses are less than the given design stresses, therefore the joint is safe.

**(i) A 50 mm diameter solid shaft** is welded to a flat plate by 10 mm fillet weld. Find the maximum torque that the welded joint can sustain if the maximum shear stress intensity in the weld material is not to exceed 80 MPa.

Given: d = 50 mm, s = 10 mm, τmax = 80 MPa.

Let T = Maximum torque that the welded joint can sustain. We know that the maximum shear stress (τmax), τmax = 2.83T / (πsd^{2}). 80 = 2.83T / (π × 10 × 50^{2}), T = 80 × 78550 / 2.83 = 2.22 × 10^{6} N-mm = 2.22 kN-m.

**A plate 1 m long, 60 mm thick** is welded to another plate at right angles to each other by 15 mm fillet weld. Find the maximum torque that the welded joint can sustain if the permissible shear stress intensity in the weld material is not to exceed 80 MPa.

Given: l = 1 m = 1000 mm, t = 60 mm, s = 15 mm, τ = 80 MPa.

Let T = Maximum torque that the welded joint can sustain. We know that the maximum shear stress (τmax), τmax = 4.242T / (s × l^{2}). 80 = 4.242T / (15 × 1000^{2}), T = 80 × 10^{6} / 0.283 = 283 × 10^{6} N-mm = 283 kN-m.

**A plate 100 mm wide and 12.5 mm thick** is to be welded to another plate by means of parallel fillet welds. The plates are subjected to a load of 50 kN. Find the length of the weld so that the maximum stress does not exceed 56 MPa. Consider the joint first under static loading and then under fatigue loading.

Given: Width = 100 mm, Thickness = 12.5 mm, P = 50 kN, τ = 56 MPa.

**Length of weld for static loading**: Let l = Length of weld, and s = Size of weld = Plate thickness = 12.5 mm. We know that the maximum load which the plates can carry for double parallel fillet welds (P), 50 × 10^{3} = 1.414 × s × l × τ. 50 × 10^{3} = 1.414 × 12.5 × l × 56, l = 50 × 10^{3} / 990 = 50.5 mm. Adding 12.5 mm for starting and stopping of weld run, we have l = 50.5 + 12.5 = 63 mm.

**Length of weld for fatigue loading**: From Table 10.6, we find that the stress concentration factor for parallel fillet welding is 2.7. Permissible shear stress, τ = 56 / 2.7 = 20.74 N/mm^{2}. We know that the maximum load which the plates can carry for double parallel fillet welds (P), 50 × 10^{3} = 1.414 × s × l × τ. 50 × 10^{3} = 1.414 × 12.5 × l × 20.74, l = 50 × 10^{3} / 367 = 136.2 mm. Adding 12.5 mm for starting and stopping of weld run, we have l = 136.2 + 12.5 = 148.7 mm.

**A double riveted lap joint** is made between 15 mm thick plates. The rivet diameter and pitch are 25 mm and 75 mm respectively. If the ultimate stresses are 400 MPa in tension, 320 MPa in shear, and 640 MPa in crushing, find the minimum force per pitch which will rupture the joint.

Given: t = 15 mm, d = 25 mm, p = 75 mm, σtu = 400 MPa, τu = 320 MPa, σcu = 640 MPa.

First of all, let us find the tearing resistance of the plate, shearing resistance, and crushing resistance of the rivet.

**(i) Tearing resistance of the plate**: We know that tearing resistance of the plate per pitch length, Pt = (p - d) × t × σtu. Pt = (75 - 25) × 15 × 400 = 300000 N.

**(ii) Shearing resistance of the rivets**: Since the joint is double riveted butt joint, therefore the strength of two rivets in double shear is taken. We know that shearing resistance of the rivets, Ps = n × 2 × (π/4) × d^{2} × τu. Ps = 2 × 2 × (π/4) × (25)^{2} × 320 = 314200 N.

**(iii) Crushing resistance of the rivets**: Since the joint is double riveted, therefore the strength of two rivets is taken. We know that crushing resistance of the rivets, Pc = n × d × t × σcu. Pc = 2 × 25 × 15 × 640 = 480000 N.

Strength of the joint = (Least of Pt, Ps, and Pc) = 300000 N or 300 kN.

**Actual stresses produced in the plates and rivets**: Since the factor of safety is 4, therefore safe load per pitch length of the joint = 300000 / 4 = 75000 N.

Let σta, τa, and σca be the actual tearing, shearing, and crushing stresses produced with a safe load of 75000 N in tearing, shearing, and crushing.

We know that actual tearing resistance of the plates (Pta), 75000 = (p - d) × t × σta. 75000 = (75 - 25) × 15 × σta, σta = 75000 / 750 = 100 N/mm^{2} = 100 MPa.

Actual shearing resistance of the rivets (Psa), 75000 = n × (π/4) × d^{2} × τa. 75000 = 2 × (π/4) × (25)^{2} × τa, τa = 75000 / 982 = 76.4 N/mm^{2} = 76.4 MPa.

Actual crushing resistance of the rivets (Pca), 75000 = n × d × t × σca. 75000 = 2 × 25 × 15 × σca, σca = 75000 / 750 = 100 N/mm^{2} = 100 MPa.

**A double riveted double cover butt joint** in plates 20 mm thick is made with 25 mm diameter rivets at 100 mm pitch. The permissible stresses are: σt = 120 MPa, τ = 100 MPa, σc = 150 MPa. Find the efficiency of joint, taking the strength of the rivet in double shear as twice that of single shear.

Given: t = 20 mm, d = 25 mm, p = 100 mm, σt = 120 MPa, τ = 100 MPa, σc = 150 MPa.

First of all, let us find the tearing resistance of the plate, shearing resistance, and crushing resistance of the rivet.

**(i) Tearing resistance of the plate**: We know that tearing resistance of the plate per pitch length, Pt = (p - d) × t × σt. Pt = (100 - 25) × 20 × 120 = 180000 N.

**(ii) Shearing resistance of the rivets**: Since the joint is double riveted butt joint, therefore the strength of two rivets in double shear is taken. We know that shearing resistance of the rivets, Ps = n × 2 × (π/4) × d^{2} × τ. Ps = 2 × 2 × (π/4) × (25)^{2} × 100 = 196375 N.

**(iii) Crushing resistance of the rivets**: Since the joint is double riveted, therefore the strength of two rivets is taken. We know that crushing resistance of the rivets, Pc = n × d × t × σc. Pc = 2 × 25 × 20 × 150 = 150000 N.

Strength of the joint = (Least of Pt, Ps, and Pc) = 150000 N.

**Efficiency of the joint**: We know that the strength of the unriveted or solid plate, P = p × t × σt. P = 100 × 20 × 120 = 240000 N.

Efficiency of the joint = (Least of Pt, Ps, and Pc) / P = 150000 / 240000 = 0.625 or 62.5%.


Besides potential performance degradation, filtering whole tables in DAX can lead to unexpected results. This post explores one example.

Consider three measures:

**1 Sales** = SUM(Sales[SalesAmount])
**2 All Product Balance** = CALCULATE([1 Sales], REMOVEFILTERS('Product'))
**3 Single Quantity Balance** = CALCULATE([1 Sales], FILTER(Sales, Sales[Quantity] = 1))

These measures, sliced by product color, yield expected results:
- [1 Sales] is a simple SUM.
- [2 All Product Balance] shows the total of [1 Sales] for all colors, ignoring filters on 'Product'.
- [3 Single Quantity Balance] shows sales where Quantity is 1, resulting in lower figures than [1 Sales].

Now, consider the measure:
**4 All Product Single Quantity Balance** = CALCULATE([2 All Product Balance], FILTER(Sales, Sales[Quantity] = 1))

If sliced by product color, what results do you expect? You might anticipate the same number for every color, equal to the grand total of [3 Single Quantity Balance].

However, the actual results may be unexpected due to expanded tables. When filtering a whole table in FILTER, it's actually an expanded table that includes related tables. In this case, the expanded version of 'Sales' includes 'Product'. Removing filters from 'Product' inside [2 All Product Balance] doesn't matter, as the expanded version of 'Sales' already respects filters on colors.

To fix this issue, filter columns instead of tables:
**4 All Product Single Quantity Balance fixed** = CALCULATE([2 All Product Balance], Sales[Quantity] = 1)

This revised measure yields more sensible results. The key takeaway is to avoid filtering whole tables in DAX and instead filter specific columns to prevent unexpected results due to expanded tables.


Log concave functions have interesting and useful properties. To understand these properties, we first need to define convex, concave, and log concave functions.

A function *f*(*x*) is **convex** if the line segment joining two points on the graph lies above the graph. Mathematically, this is expressed as *f*(*tx* + (1-*t*)*y*) ≤ *t* *f*(*x*) + (1-*t*) *f*(*y*) for every *t* between 0 and 1, and for every *x* and *y*.

A function *f*(*x*) is **concave** if –*f*(*x*) is convex. Equivalently, the line connecting two points on the graph lies below the graph. This can be represented by reversing the direction of the inequality for convexity.

A function *f*(*x*) is **log concave** if log(*f*(*x*)) is concave.

Some key properties of log concave functions include:
- The Laplace transform of a non-negative function is log convex.
- The running average of a log concave function is also log concave.
- If a random variable has a log concave probability density function (PDF), then the cumulative distribution function (CDF) is also log concave.
- The convolution of two log concave functions is log concave.
- If two independent random variables have log-concave PDFs, then their sum also has a log concave PDF.

Additionally, the product of log concave functions is log concave. A function *f*(*x*) is log concave if and only if for every *t* between 0 and 1 and for every *x* and *y*, *f*(*tx* + (1-*t*)*y*) ≥ *f*(*x*)^*t* *f*(*y*)^(1-*t*). For a smooth function *f*(*x*), it is log concave if and only if the inequality *f* ∇^2 *f* ≤ ∇*f* ⋅ ∇*f* holds everywhere.

Examples of log concave functions include:
- The exponential function *e*^(*ax*)
- The inverse logit function *e*/(*e*^*x* + 1)
- The function ∏ *x* / ∑ *x*_*i*
- The function *x* for *a* ≥ 0
- The determinant is a log concave function on positive definite matrices

For more information, see Stephen Boyd's book Convex Optimization. Lectures from his courses on convex optimization are available on YouTube, and other course materials can be found on the Stanford website.

Regarding specific questions about log concave functions:
- For a reference on the running average of a log concave function being log concave, see Stephen Boyd's book.
- To interpret a concave function mathematically, consider its definition and properties.
- The function *f*(*x*) = *p* + (1-2*p)*Q(*x*) is not necessarily log concave for all *p* (0 < *p* < 1), but it can be log concave under specific conditions, such as when *p* = 1/3 and *Q*(*x*) = *erf*(*x*).
- The sum of infinitely many log concave functions is not necessarily log concave.


Dividing fractions by a whole number involves converting the whole number into a fraction, finding the reciprocal of that fraction, and multiplying the result by the first fraction. To do this, follow these steps:

1. Write the problem, including the fraction and the whole number you need to divide it by. For example, 2/3 ÷ 4.
2. Convert the whole number into a fraction by placing it over 1. In this case, 4 becomes 4/1.
3. Change the division sign to a multiplication sign and find the reciprocal of the whole number fraction. The reciprocal of 4/1 is 1/4, so the problem becomes 2/3 x 1/4.
4. Multiply the numerators and denominators of the fractions. 2 x 1 = 2 and 3 x 4 = 12, so the result is 2/12.
5. Simplify the fraction by finding the greatest common divisor of the numerator and denominator. In this case, 2 is the greatest common divisor, so dividing both numbers by 2 gives 1/6.

To illustrate this process, consider the following examples:

* 1 1/4 x 3 1/3: Convert the mixed numbers to improper fractions (5/4 and 10/3), multiply (50/12), and simplify (4 1/6).
* 6 2/3 divided by 4: Convert the mixed number to an improper fraction (20/3), convert 4 to a fraction (4/1), multiply (20 x 4 = 80 over 3 x 1 = 3), and simplify (26 2/3).
* 2/3 divided by 2: Convert 2 to a fraction (2/1), find the reciprocal (1/2), and multiply (2/3 x 1/2 = 1/3).
* 2 divided by 1/3: Find the reciprocal of 1/3 (3/1) and multiply (2 x 3 = 6).
* 11 divided by 1/5: Find the reciprocal of 1/5 (5/1) and multiply (11 x 5 = 55).
* 4 divided by 2/3: Convert 4 to a fraction (4/1), find the reciprocal of 2/3 (3/2), and multiply (4/1 x 3/2 = 12/2 = 6).
* 3 divided by 2/3: Convert 3 to a fraction (3/1), find the reciprocal of 2/3 (3/2), and multiply (3/1 x 3/2 = 9/2 = 9).

Tips for dividing fractions by whole numbers include:

* Remembering the mnemonic "Dividing fractions is easy as pie, flip the second number and multiply!"
* Using the KCF/KFC method: Keep the first number, Change to multiplication, Flip the last number.
* Cross-canceling before multiplying to simplify the process.
* Keeping track of the sign when working with negative fractions.
* Simplifying before multiplying instead of at the end.

Common mistakes to avoid include:

* Taking the reciprocal of the wrong fraction.
* Forgetting to change the division sign to a multiplication sign.
* Not simplifying the fraction after multiplying.

By following these steps and tips, you can easily divide fractions by whole numbers and simplify the results.


ST_Simplify — Returns a simplified version of a geometry using the Douglas-Peucker algorithm.

**Syntax**
```sql
geometry ST_Simplify(geomA, float tolerance)
geometry ST_Simplify(geomA, float tolerance, boolean preserveCollapsed)
```

**Description**
Returns a simplified version of the given geometry using the Douglas-Peucker algorithm. This function is applicable to (multi)lines, (multi)polygons, and GeometryCollections. Simplification occurs on an object-by-object basis.

**Parameters**
- `geomA`: the input geometry
- `tolerance`: the simplification tolerance
- `preserveCollapsed`: a flag to retain objects that would otherwise be too small given the tolerance

**Notes**
- The `preserveCollapsed` flag is useful for rendering engines to avoid having large numbers of very small objects disappear from a map.
- The returned geometry might lose its simplicity and topology may not be preserved, resulting in invalid geometries. Use `ST_SimplifyPreserveTopology` to preserve topology.

**Availability**
1.2.2

**Example**
A circle simplified with different tolerances becomes a polygon with a decreasing number of points. If the tolerance is too high, the geometry may disappear.
```sql
SELECT
  ST_Npoints(geom) AS np_before,
  ST_NPoints(ST_Simplify(geom,0.1)) AS np01_notbadcircle,
  ST_NPoints(ST_Simplify(geom,0.5)) AS np05_notquitecircle,
  ST_NPoints(ST_Simplify(geom,1)) AS np1_octagon,
  ST_NPoints(ST_Simplify(geom,10)) AS np10_triangle,
  (ST_Simplify(geom,100) is null) AS np100_geometrygoesaway
FROM (SELECT ST_Buffer('POINT(1 3)', 10,12) As geom) AS foo;
```
Result:
```
np_before | np01_notbadcircle | np05_notquitecircle | np1_octagon | np10_triangle | np100_geometrygoesaway
-----------+-------------------+---------------------+-------------+---------------+------------------------
49 | 33 | 17 | 9 | 4 | t
```


# Unknown Number Problem

16% of an unknown number is 21 less than the unknown number itself. We need to find the natural unknown number.

To solve this problem, we can use algebraic equations and percentage calculations. Let's denote the unknown number as "x". The equation can be set up as 0.16x = x - 21.

We also have some tips and related online calculators that can help with percentage calculations, linear equations, and quadratic equations.

## Required Mathematical Knowledge

To solve this word problem, we need knowledge of percentages, algebraic equations, and basic arithmetic operations.

## Similar Math Problems

- Percentages: 35% of what number is 35?
- Pupils: A school has 350 girls, and the other 30% of the total number of pupils are boys. How many pupils does the school have?
- Cows: An agricultural cooperative increased the number of housed cows by 14% to 285 units. By how many cows did the cooperative increase the number of cows?
- Holidays: Children's tickets to the swimming pool cost x €, and an adult ticket is € 2 more expensive. There were m children in the swimming pool and adults three times less. How many euros did the treasurer make from pool entry?
- Profit Gain: If 5% more is gained by selling an article for Rs. 350 than by selling it for Rs. 340, the cost of the article is:
- Ethnicity: The share of ethnicity XY is 26%, which is 1/9 more than in the prewar period. What was the share of that ethnicity in the pre-war period?
- Enrollment: The enrollment at a local college increased 4% over last year's enrollment of 8548. Find the increase in enrollment and the current enrollment.
- Percentages: 52 is what percent of 93?
- Sales Off: The price has decreased by 20%. How many percents do I have to raise the new price to be the same as before the cut?
- Girls: The children's competition was attended by 63 girls, which is 30% of all children's participants. How many children attended this competition?
- Persons: Persons surveyed: 100 with result: Volleyball = 15% Baseball = 9% Sepak Takraw = 8% Pingpong = 8% Basketball = 60%. Find the average number of people who like Basketball and Volleyball.
- TVs: Production of television sets increased from 3,500 units to 4,200 units. Calculate the percentage of production increase.
- Cinema Tickets: Cinema sold 180 tickets this Thursday, which is 20%. Monday 14%, Tuesday 6%, Wednesday 9%, Friday 24%, Saturday 12%, and Sunday 15%. How many tickets were sold per week?
- Frameworks: Calculate how many percent will increase the length of an HTML document if any ASCII character is unnecessarily encoded as a hexadecimal HTML entity.
- Percents - Easy: How many percent is 432 out of 434?
- Given: Given 2x = 0.125, find the value of x.
- Simplify 2: Simplify the expression: 5ab - 7 + 3ba - 9.


Amplitude modulation is a technique used to transmit electric signals containing information via radio waves. The electric signal to transmit is represented by a mathematical function f(t), and the carrier signal is cos wt. The amplitude of cos wt changes in terms of f(t) as follows: F(t) = (1 + f(t)) * cos wt. This is called amplitude modulation because the amplitude of the carrier cos wt changes in terms of f(t).

To illustrate this concept, consider a simple sinusoidal signal f(t) = m cos st. The amplitude modulated signal F(t) becomes F(t) = (1 + m cos st) * cos wt. An interactive applet can be used to explore the amplitude modulated signal F(t) as the amplitude m of the signal to transmit changes.

The tutorial to understand amplitude modulation involves the following steps:
1. Initialize the applet by clicking on the "click here to start" button and maximizing the window.
2. Set the parameter m to zero using the slider, resulting in no modulation, and explain the graph obtained.
3. Set the parameter m to 1 using the slider and explain the resulting graph.
4. Set the parameter m to values larger than 1 using the slider and explain the graph obtained, observing the changes in the amplitude modulated signal F(t) as m increases.


In math, the interval of convergence is significant when working with power series. A power series is a sum that goes on forever and looks like ∑∞_{n=0} a_{n} (x-c)^{n}, where a_{n} is the coefficient, c is the center of the series, and x is a variable. The interval of convergence refers to the set of all x-values for which this series converges.

Determining the interval of convergence is crucial for understanding the behavior of the series and ensuring its practical utility in various applications, such as solving differential equations, modeling phenomena in physics, and analyzing functions in engineering. An interval of convergence calculator is essential for mathematicians, scientists, and engineers as it simplifies finding the interval where a power series converges.

The calculator automates the complex and often tedious process of calculating convergence intervals, making it accessible for users who might not have an extensive background in advanced mathematics. The key features of an interval of convergence calculator include:

- Automation of Calculations: By inputting the series and its coefficients, the calculator can quickly process the information and return the interval of convergence.
- Accuracy and Precision: These calculators use proven math methods to ensure correct results.
- User-Friendly Interface: Most calculators have a straightforward interface, allowing users to easily input data and interpret results without understanding the underlying algorithms.

Finding the interval of convergence involves determining the set of all x-values for which a power series converges. This process typically includes several steps:

1. Ratio Test or Root Test: These are the most common methods used to determine the series' convergence. The ratio test checks the limit of the absolute value of the ratio between one term and the next in a sequence. If this limit is less than 1, the series converges.
2. Determining the Radius of Convergence R: This is derived from the limit found using the ratio or root test. The radius of convergence is the distance from the center to the boundary points of the interval where the series converges.
3. Testing Endpoints: Once the radius of convergence is found, the endpoints of the interval [c - R, c + R] must be tested individually to determine whether they should be included in the interval of convergence.
4. Combining Results: The interval of convergence is then constructed by combining the results from the previous steps. If both endpoints converge, they are included in the interval; if not, they are excluded.

For power series, the steps involved in finding the interval of convergence are:

1. Identify the Power Series: Start with the given power series.
2. Apply the Ratio Test: This series converges if (x - c) L < 1, which implies the following.
3. Calculate the Radius of Convergence R: R = 1 / L. The interval of convergence is (c - R, c + R).
4. Test the Endpoints: Substitute c ± R into the original series to check for convergence at these points.
5. Compile the Interval: Based on the results from the endpoint tests, determine whether the endpoints are included or excluded, thus forming the interval of convergence.

The radius of convergence R is a crucial concept related to the interval of convergence. It represents the distance from the center C of the power series to the points where it ceases to converge. The radius of convergence can be found using the ratio test or the root test. Knowing R provides insight into how rapidly the terms of the series decrease and thus, how quickly the series converges.

An interval of convergence calculator is a valuable tool that makes studying and using power series easier and more efficient. Understanding and using the interval of convergence is very important for getting the best results from power series in different areas like education, research, and real-life applications. The calculator is useful as an educational tool, in research, and in practical problem-solving.


*Always 12* is a game that provides students with the opportunity to add multiple numbers at once, using the numbers 1-6 to reach a goal of 12. This game reinforces the part-part-whole relationship among numbers and introduces the commutative property of addition, where the order of numbers does not change the result. For example, 4+3=3+4. The game also helps students think about subtraction in a different way, considering how far a number is from 12 and making substitutions using their cards.

This game is suitable for children who are comfortable adding numbers from 1-6 mentally and are ready for the additional challenge of adding more numbers. Students will have opportunities to add 3 numbers together, compare the sum to 12, and determine the missing addend to make 12. A template for making *Always 12* cards is included, and other number cards, such as those from a standard deck of cards, can also be used.

As students master this game, *Foxes Boxes* may provide an additional challenge. The recommended number of players is 2-4, and this game is suitable for advanced players.

## Standards Addressed

**Common Core Standards**

The game *Always 12* addresses various Common Core Standards, including:

**Kindergarten**

* Counting and Cardinality:
  - K.CC.1: Count to 100 by ones and by tens.
  - K.CC.2: Count forward beginning from a given number within the known sequence.
  - K.CC.4: Understand the relationship between numbers and quantities.
  - K.CC.5: Count to answer "how many?" questions about as many as 20 things.

* Operations and Algebraic Thinking:
  - K.OA.1: Represent addition and subtraction with objects, fingers, mental images, drawings, sounds, acting out situations, verbal explanations, expressions, or equations.
  - K.OA.2: Solve addition and subtraction word problems, and add and subtract within 10.
  - K.OA.3: Decompose numbers less than or equal to 10 into pairs in more than one way.
  - K.OA.4: For any number from 1 to 9, find the number that makes 10 when added to the given number.
  - K.OA.5: Fluently add and subtract within 5.

* Number and Operations in Base Ten:
  - K.NBT.1: Compose and decompose numbers from 11 to 19 into ten ones and some further ones.

**First Grade**

* Operations and Algebraic Thinking:
  - 1.OA.1: Use addition and subtraction within 20 to solve word problems involving situations of adding to, taking from, putting together, taking apart, and comparing.
  - 1.OA.3: Apply properties of operations as strategies to add and subtract.
  - 1.OA.4: Understand subtraction as an unknown-addend problem.
  - 1.OA.5: Relate counting to addition and subtraction.
  - 1.OA.6: Add and subtract within 20, demonstrating fluency for addition and subtraction within 10.
  - 1.OA.7: Understand the meaning of the equal sign, and determine if equations involving addition and subtraction are true or false.
  - 1.OA.8: Determine the unknown whole number in an addition or subtraction equation relating three whole numbers.

**Second Grade**

* Operations and Algebraic Thinking:
  - 2.OA.2: Fluently add and subtract within 20 using mental strategies. By end of Grade 2, know from memory all sums of two one-digit numbers.


Understanding Least Common Multiples is crucial for working with fraction problems. The provided worksheets generate 20 fractions problems with exponents per worksheet, catering to various levels of difficulty. Registering for a free trial allows access to print five sets of worksheets.

The fractions worksheets are categorized into different levels of difficulty, including easy, medium, and hard. They cover a range of topics, such as:
- Adding and subtracting fractions
- Dividing fractions, specifically proper fractions by whole numbers
- Reducing fractions
- Ordering fractions
- Adding fractional inches
- Multiplying fractions
- Finding the Greatest Common Factor of number sets
- Comparing fractions to determine if they are greater than, less than, or equal

The worksheets are suitable for various age groups, including Kindergarten, 1st Grade, 2nd Grade, and Year 6 (age 10-11). In Year 6, the focus is on equivalent fractions, using common factors to simplify fractions, and cancelling.

The worksheets offer flexibility, allowing users to:
- Select the denominators of the fractions
- Choose the type of problems
- Generate 10 to 30 problems per worksheet
- Select 3 or 4 digits to the right of the decimal
- Generate 10 fraction addition or subtraction problems per worksheet
- Generate 6 Prime Factorization Tree problems per worksheet

Key topics covered include:
- Simplifying fractions
- Adding, subtracting, multiplying, and dividing fractions
- Percentages
- Equivalent fractions
- Common factors
- Cancelling

The worksheets are designed to meet the challenges set by the Programme of Study, providing a comprehensive resource for teaching and learning fractions.


**Assignment 1**

1. Harvard Law School courses often have assigned seating to facilitate the “Socratic method.” Suppose that there are 100 first-year Harvard Law students, and each takes two courses: Torts and Contracts. Both are held in the same lecture hall (which has 100 seats), and the seating is uniformly random and independent for the two courses.

(a) Find the probability that no one has the same seat for both courses.

(b) Find a simple but accurate approximation to the probability that no one has the same seat for both courses.

(c) Find a simple but accurate approximation to the probability that at least two students have the same seat for both courses.

2. There are 100 passengers lined up to board an airplane with 100 seats (with each seat assigned to one of the passengers). The first passenger in line crazily decides to sit in a randomly chosen seat (with all seats equally likely). Each subsequent passenger takes his or her assigned seat if available, and otherwise sits in a random available seat. What is the probability that the last passenger in line gets to sit in his or her assigned seat?

**Assignment 2**

1. Raindrops are falling at an average rate of 20 drops per square inch per minute. What would be a reasonable distribution to use for the number of raindrops hitting a particular region measuring 5 inches^2 in t minutes? Using your chosen distribution, compute the probability that the region has no raindrops in a given 3-second time interval.

2. Let X be a random day of the week, coded so that Monday is 1, Tuesday is 2, etc. (so X takes values 1, 2,..., 7, with equal probabilities). Let Y be the next day after X (again represented as an integer between 1 and 7). Do X and Y have the same distribution? What is P(X)?

**Assignment 3**

1. For a group of 7 people, find the probability that all 4 seasons (winter, spring, summer, fall) occur at least once each among their birthdays, assuming that all seasons are equally likely.

2. Alice attends a small college in which each class meets only once a week. She is deciding between 30 non-overlapping classes. There are 6 classes to choose from for each day of the week, Monday through Friday. Trusting in the benevolence of randomness, Alice decides to register for 7 randomly selected classes out of the 30, with all choices equally likely. What is the probability that she will have classes every day, Monday through Friday?

**Assignment 4**

1. Is it possible that an event is independent of itself? If so, when?

2. Is it always true that if A and B are independent events, then Ac and Bc are independent events? Show that it is, or give a counterexample.

**Assignment 5**

1. Give an example of 3 events A, B, C which are pairwise independent but not independent.

2. A bag contains one marble which is either green or blue, with equal probabilities. A green marble is put in the bag (so there are 2 marbles now), and then a random marble is taken out. The marble taken out is green. What is the probability that the remaining marble is also green?

**Assignment 6**

A group of n players decide to play an exciting game of Rock-Paper Scissors. As you may recall, Rock smashes Scissors, Scissors cuts Paper, and Paper covers Rock. Usually, this game is played with 2 players, but it can be extended to more players as follows. If exactly 2 of the 3 choices appear when everyone reveals their choice, say a, b ∈ {Rock, Paper, Scissors} where a beats b, the game is decisive: the players who chose a win, and the players who chose b lose. Otherwise, the game is indecisive and the players play again.

(a) Find the joint PMF of X, Y, Z.

(b) Find the probability that the game is decisive.

(c) What is the probability that the game is decisive for n = 5? What is the limiting probability that a game is decisive as n → ∞?

**Assignment 7**

1. A spam filter is designed by looking at commonly occurring phrases in spam. Suppose that 80% of email is spam. In 10% of the spam emails, the phrase “free money” is used, whereas this phrase is only used in 1% of non-spam emails. A new email has just arrived, which does mention “free money”. What is the probability that it is spam?

**Assignment 8**

1. A crime is committed by one of two suspects, A and B. Initially, there is equal evidence against both of them. In further investigation at the crime scene, it is found that the guilty party had a blood type found in 10% of the population. Suspect A does match this blood type, whereas the blood type of Suspect B is unknown.

(a) Given this new information, what is the probability that A is the guilty party?

(b) Given this new information, what is the probability that B’s blood type matches that found at the crime scene?

**Assignment 9**

1. You are going to play 2 games of chess with an opponent whom you have never played against before. Your opponent is equally likely to be a beginner, intermediate, or a master.

(a) What is your probability of winning the first game?

(b) Congratulations: you won the first game! Given this information, what is the probability that you will also win the second game?

(c) Explain the distinction between assuming that the outcomes of the games are independent and assuming that they are conditionally independent given the opponent’s skill level. Which of these assumptions seems more reasonable, and why?


# Two-Point Form

To solve point-slope form problems, we use the formula with two given points on the line: (*x*_{1}, *y*_{1}) and (*x*_{2}, *y*_{2}). The slope of the line is calculated as [(*y*_{2} - *y*_{1})/(*x*_{2} - *x*_{1})]. Given that the line passes through (*x*_{1}, *y*_{1}), the linear equation in point-slope form is *y* = ((*y*_{2} - *y*_{1})/(*x*_{2} - *x*_{1}))⋅(*x* - *x*_{1}) + *y*_{1}, which is essentially the two-point form of the linear equation.

This two-point form is another version of the point-slope form. Alternatively, using (*x*_{2}, *y*_{2}), the linear equation in two-point form can be written as *y* = [(*y*_{2} - *y*_{1})/(*x*_{2} - *x*_{1})]⋅(*x* - *x*_{2}) + *y*_{2}.

## Example

To illustrate, consider finding the linear equation given two points. Instead of directly writing the equation in two-point form, it's easier to first find the slope and then use the point-slope form.

Given points (2, 1) and (5, 4), the change in *x* is 3 (5 - 2) and the change in *y* is 3 (4 - 1). Thus, the slope *m* = 3/3 = 1. Since the line passes through (2, 1), the linear equation in point-slope form is *y* = 1(*x* - 2) + 1. Converting this to slope-intercept form yields *y* = *x* - 1.

## Example: Another Solution

Choosing the other point (5, 4) and repeating the process: the change in *x* is still 3 (5 - 2), and the change in *y* is 3 (4 - 1), resulting in a slope *m* = 1. With the line passing through (5, 4), the linear equation in point-slope form is *y* = 1(*x* - 5) + 4. Converting to slope-intercept form again yields *y* = *x* - 1, demonstrating that the same answer can be obtained regardless of the point chosen for the calculation.


Fraction concepts can be challenging for students to grasp and teachers to teach. Fraction operations, such as multiplication and division, can be particularly difficult because students struggle to connect these actions with whole numbers. To develop these skills, students need extensive experience and practice. Using picture books can help students visualize fraction operations and compare the effects of multiplying and dividing whole numbers with fractions.

Two fraction picture books can serve as a great introduction to fraction multiplication and division. The first book, "The Multiplying Menace," tells the story of Peter, the son of the King and Queen, who celebrates his tenth birthday when Rumpelstiltskin returns to fulfill a promise. Rumpelstiltskin uses a magic stick to multiply whole numbers by whole numbers, resulting in a larger amount, and whole numbers by fractions, resulting in a smaller amount. The story helps students understand the concept of multiplication and how it affects different types of numbers.

Key concepts and questions to ponder include:
- What is multiplication?
- What happens when we multiply a whole number by a whole number?
- What happens when we multiply a whole number by a fraction?
- What happens when we multiply a number by zero?

Activity ideas include:
- Creating a T-chart to brainstorm situations where more or fewer objects resulted from multiplication
- Having students create a chart with examples of multiplication with whole numbers and fractions
- Using the book to create problems, such as "When Peter wanted to change his dad's face back to one nose instead of six, what did he multiply by?"

The second book, "The Multiplying Menace Divides," introduces the concept of division. The story follows Peter as he discovers that Rumpelstiltskin and a witch named Matilda are using a magic stick called "The Great Divide" to divide the world into frogs. The characters use the magic stick to divide whole numbers by whole numbers, resulting in a smaller amount, and whole numbers by fractions, resulting in a larger amount.

Key concepts and questions to ponder include:
- What is division?
- What happens when we divide a whole number by a whole number?
- What happens when we divide a whole number by a fraction?
- What happens when we divide a number by zero?

Activity ideas include:
- Creating a T-chart to brainstorm situations where more or fewer objects resulted from division
- Having students create a chart with examples of division with whole numbers and fractions
- Using the book to create problems, such as "When Matilda changed a horse into four smaller horses, what did she divide by?"

Both books provide a engaging way to introduce fraction operations and help students develop a deeper understanding of these concepts. By using these stories and activity ideas, teachers can create a comprehensive and interactive lesson plan that meets the needs of their students.


Angular Acceleration

Mil/Square Month to Gradian/Square Month conversion: 781 Mil/Square Month is equal to 48.81 Gradian/Square Month. The conversion formula is: 1 Mil/Square Month = 0.0625 Gradian/Square Month. To convert, multiply the number by 0.0625.

Example: 781 Mil/Square Month = 781 × 0.0625 = 48.81 Gradian/Square Month.

Mil per square month (mil/month2) and Gradian per square month (grad/month2) are units of measurement for angular acceleration.

Conversion Table:
| Mil/Square Month | Gradian/Square Month |
| --- | --- |
| 781 | 48.81 |
| 782 | 48.88 |
| 783 | 48.94 |
| 784 | 49 |
| 785 | 49.06 |
| 786 | 49.13 |
| 787 | 49.19 |
| 788 | 49.25 |
| 789 | 49.31 |
| 790 | 49.38 |

781 mil/square month is also equal to:
- 6.3522578497835e-12 degree/square second
- 6.3522578497835e-18 degree/square millisecond
- 6.3522578497835e-24 degree/square microsecond
- 6.3522578497835e-30 degree/square nanosecond
- 2.2868128259221e-8 degree/square minute
- 0.000082325261733194 degree/square hour
- 0.04741935075832 degree/square day
- 2.32 degree/square week
- 43.93 degree/square month
- 6326.1 degree/square year

- 1.1086781441438e-13 radian/square second
- 1.1086781441438e-19 radian/square millisecond
- 1.1086781441438e-25 radian/square microsecond
- 1.1086781441438e-31 radian/square nanosecond
- 3.9912413189176e-10 radian/square minute
- 0.0000014368468748103 radian/square hour
- 0.00082762379989075 radian/square day
- 0.040553566194647 radian/square week
- 0.76674495701676 radian/square month
- 110.41 radian/square year

- 7.0580642775372e-12 gradian/square second
- 7.0580642775372e-18 gradian/square millisecond
- 7.0580642775372e-24 gradian/square microsecond
- 7.0580642775372e-30 gradian/square nanosecond
- 2.5409031399134e-8 gradian/square minute
- 0.000091472513036883 gradian/square hour
- 0.052688167509244 gradian/square day
- 2.58 gradian/square week
- 48.81 gradian/square month
- 7029 gradian/square year

Note: The conversion tools and data are provided for general information purposes only and should be validated with an authority for accuracy.


**Place Value Through Thousandths**

Numbers less than 1 can be written using decimal place value. A decimal is a number with a decimal point (.) that separates the whole numbers from the part that represents part of one whole. Each digit to the right of the decimal point has its own value.

The place-value chart shows the names of the places. For example, the decimal 4.853 is made up of 4 ones, 8 tenths, 5 hundredths, and 3 thousandths. Use place value to read a decimal or to determine the value of a digit in a decimal numeral. In the decimal system, each place to the left has 10 times the value of the place on its right.

To read a decimal, say the whole number first if there is one, then say "and" for the decimal point, and finally say the rest of the number as a whole number, followed by the place of the last digit. For example, 62.37 is read as "sixty-two and thirty-seven hundredths".

Equivalent decimals are decimals that have the same value. Adding a "0" to the right side of a decimal does not change its value. For example, 0.68 = 0.680. However, adding a "0" immediately after the decimal point does change its value. For example, 0.68 ≠ 0.068.

**Practice**

Write each number in standard form:
- 36 hundredths = 0.36
- 3 and 5 hundredths = 0.35
Write the digit for each place in 1:
- Tens: 0
- Tenths: 0
- Thousandths: 1
Name the place value of the digit 3 in each number:
- 45.3: tenths
- 3,004: thousands

**Ways to Write Numbers - Review**

There are three ways to write numbers: word form, standard form, and expanded form. For example:
- Word form: One billion, four hundred seven million, seven hundred thirty-nine thousand
- Standard form: 1,407,739,000
- Expanded form: 1,000,000,000 + 400,000,000 + 7,000,000 + 700,000 + 30,000 + 9,000

**Homework**

Complete the exercises in Math Workbook p. P 1-3. The homework will be presented and noted as completed when the agenda is checked in the morning.


# Place value

**Place value understanding** is crucial in mental strategies, and a simple approach to it is through counting. Organizing objects into groups of ten, one hundred, etc., makes counting a set easier. Students should experience bundling individual objects, such as counters or icypole sticks, and linking the number of bundles and extras to the written form of symbols.

Applying counting sets, using bundles of ten, one hundred, etc., to addition and subtraction problems helps students see the system's usefulness. Grouping tens and ones is more efficient than working with ones alone, making place value learning attractive.

Renaming and decomposing units of ten (and later one hundred, one thousand, etc.) poses challenges, requiring an understanding of the conservation of number, where the object count remains constant during rearrangement.

Place value is a **multiplicative system**. Students must understand that a digit's value in any numeral depends on the count it reflects and its place. For example, 4 means four of something, and its place (e.g., hundreds) affects its value (e.g., 400). Units' significance is vital in solving multiplication problems, such as 40 × 30 relating to 4 × 3 = 12.


## Lowest Common Ancestor of a Binary Tree

The problem requires finding the lowest common ancestor (LCA) of two given nodes in a binary tree. According to the definition of LCA, it is the lowest node in the tree that has both nodes as descendants, allowing a node to be a descendant of itself.

## Approach

The solution involves using a recursive approach with a bottom-up postorder traversal. This method traverses the tree in a postorder manner, checking each node's left and right children before the current node.

## Base Case

- If the node is null, return null.
- If the current node matches either of the given nodes, return the current node.

## Recursive Cases

- **Case 1:** If both left and right children are found, the current node is the LCA.
- **Case 2:** If neither left nor right children are found, there is no LCA, so return null.
- **Case 3:** If only one of the left or right children is found, that child is the LCA.

## Solution

```javascript
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function (root, p, q) {
    const dfs = (node, p, q) => {
        if (!node) return null;
        if (node === p || node === q) return node;
        const left = dfs(node.left, p, q);
        const right = dfs(node.right, p, q);
        if (left && right) return node;
        if (!left && !right) return null;
        if (left || right) return left || right;
    };
    return dfs(root, p, q);
};
```

This solution uses a recursive depth-first search (DFS) function to traverse the binary tree and find the LCA of the two given nodes. The function checks each node's children and returns the node that is the LCA of the two given nodes.


R&S®Essentials | LCR meters fundamentals

# Choosing the correct instrument: LCR meter vs. VNA

The LCR meter and the vector network analyzer (VNA) are two powerful instruments for RF and microwave engineering, each playing a crucial role in characterizing the electrical properties of components and devices. Understanding the difference between these two instruments will help you pick the perfect one for your specific needs.

## How do LCR meters work

LCR meters evaluate the electrical properties of passive components like resistors, capacitors, and inductors. The process involves:

- Applying an AC voltage or current signal to the device under test (DUT)
- Measuring the voltage and current across the DUT
- Calculating the impedance of the DUT using the measured voltage and current values
- Displaying calculated impedance values as numerical values, graphs, or charts to interpret the electrical characteristics of the DUT

This understanding of LCR meters is essential in determining the appropriate instrument for specific engineering needs.


This R Markdown document illustrates a simulation tool for group sequential survival trials, useful for validating analytic calculations when the allocation ratio is not 1:1 or the hazard ratio is far from 1.

A three-stage O'Brien-Fleming group sequential design is considered with two interim looks at 50% and 75% of the target total number of events. The first interim look is for futility only, and the second interim look is for efficacy only. Key parameters include:
- Hazard rate of the control group: 0.95 per year
- Hazard ratio of the experimental group to the control group: 0.3
- Experimental versus control group randomization ratio: 3:1
- Enrollment rate: 5 patients per month
- 2-year drop-out rate: 10%
- Fixed follow-up design with each patient followed up for 26 weeks
- Enrollment duration: 32 months, resulting in a maximum expected number of events of 32.8

The `lrstat` function is used to calculate the expected number of events and other metrics at different time points.

```r
lrstat(time=c(20,25,30,35,38.5), allocationRatioPlanned = 3,
accrualIntensity = 5,
lambda2 = 0.95/12, lambda1 = 0.3*0.95/12,
gamma1 = -log(1-0.1)/24, gamma2 = -log(1-0.1)/24,
accrualDuration = 32, followupTime = 6.5, fixedFollowup = TRUE)
```

Results show the expected number of events, subjects, and other metrics at each time point.

The `lrsim` function is used to simulate the trial and estimate the power under the alternative hypothesis.

```r
lrsim(kMax = 3, informationTime = c(0.5, 0.75, 1),
criticalValues = c(Inf, 2.34, 2.012),
futilityBounds = c(0.282, -Inf),
allocation1 = 3, allocation2 = 1,
accrualTime = 0, accrualIntensity = 5,
piecewiseSurvivalTime = 0,
stratumFraction = 1,
lambda1 = 0.3*0.95/12, lambda2 = 0.95/12,
gamma1 = -log(1-0.1)/24, gamma2 = -log(1-0.1)/24,
accrualDuration = 34, followupTime = 6.5,
fixedFollowup = TRUE,
rho1 = 0, rho2 = 0,
plannedEvents = c(16, 24, 32),
maxNumberOfIterations = 1000,
maxNumberOfRawDatasetsPerStage = 0,
seed = 12345)
```

Simulation results show that the study has a target power of 90% under the alternative hypothesis, with the following metrics:
- Cumulative rejection rates at each stage
- Cumulative futility rates at each stage
- Expected number of events, subjects, and analysis time

An additional simulation under the null hypothesis shows that the probability of futility stopping is 62%.

```r
lrsim(kMax = 3, informationTime = c(0.5, 0.75, 1),
criticalValues = c(100, 2.34, 2.012),
futilityBounds = c(0.282, -100),
allocation1 = 3, allocation2 = 1,
accrualTime = 0, accrualIntensity = 5,
piecewiseSurvivalTime = 0,
stratumFraction = 1,
lambda1 = 0.95/12, lambda2 = 0.95/12,
gamma1 = -log(1-0.1)/24, gamma2 = -log(1-0.1)/24,
accrualDuration = 34, followupTime = 6.5,
fixedFollowup = TRUE,
rho1 = 0, rho2 = 0,
plannedEvents = c(16, 24, 32),
maxNumberOfIterations = 1000,
maxNumberOfRawDatasetsPerStage = 0,
seed = 12345)
```

Results under the null hypothesis show the cumulative rejection and futility rates, expected number of events, subjects, and analysis time.


## NCERT solutions for class 9 Maths

**Statistics**

**Chapter 14**

**Exercise 14.4**

**Ex 14.4 Question 1.**
A team scored the following number of goals in a series of 10 matches: 2, 3, 4, 5, 0, 1, 3, 3, 4, 3. Find the mean, median, and mode of these scores.

**Solution:**
Number of observations (n) = 10
Mean = 2.8
Arranged data in ascending order: 0, 1, 2, 3, 3, 3, 3, 4, 4, 5
Since the number of observations is even, Median = 3
The observation 3 occurs maximum 4 times, so Mode = 3

**Ex 14.4 Question 2.**
In a mathematics test given to 15 students, the following marks (out of 100) are recorded: 41, 39, 48, 52, 46, 62, 54, 40, 96, 52, 98, 40, 42, 52, 60. Find the mean, median, and mode of this data.

**Solution:**
Number of observations (n) = 15
Mean = 54.8
Arranged data in ascending order: 39, 40, 40, 41, 42, 46, 48, 52, 52, 52, 54, 60, 62, 96, 98
Since the number of observations is odd, Median = 52
The observation 52 occurs maximum 3 times, so Mode = 52

**Ex 14.4 Question 3.**
The following observations are arranged in ascending order: 29, 32, 48, 50, x, x + 2, 72, 78, 84, 95. If the median of the data is 63, find the value of x.

**Solution:**
Number of observations (n) = 10 (even number)
Median = 63
To find the median of an even number of observations, we take the average of the two middle numbers. Since the median is 63, x + 1 = 63, so x = 62.

**Ex 14.4 Question 4.**
Find the mode of the following data: 14, 25, 14, 28, 18, 17, 18, 14, 23, 22, 14, and 18.

**Solution:**
Arranged data in ascending order: 14, 14, 14, 14, 17, 18, 18, 18, 22, 23, 25, 28
The number 14 occurs maximum 4 times, so Mode = 14

**Ex 14.4 Question 5.**
Find the mean salary of 60 workers of a factory from the given table.

**Ex 14.4 Question 6.**
Give one example of a situation in which:
(i) the mean is an appropriate measure of central tendency.
(ii) the mean is not an appropriate measure of central tendency, but the median is an appropriate measure of central tendency.

**Solution:**
(i) Mean height of family members in a family.
(ii) Median marks obtained by students in a maths test.


In this tutorial, you will learn how to perform regression using Keras and Deep Learning. You will learn how to train a Keras neural network for regression and continuous value prediction, specifically in the context of house price prediction.

Today’s post kicks off a 3-part series on deep learning, regression, and continuous value prediction. We’ll be studying Keras regression prediction in the context of house price prediction.

**Part 1:** Today we’ll be training a Keras neural network to predict house prices based on categorical and numerical attributes such as the number of bedrooms/bathrooms, square footage, zip code, etc.
**Part 2:** Next week we’ll train a Keras Convolutional Neural Network to predict house prices based on input images of the houses themselves (i.e., frontal view of the house, bedroom, bathroom, and kitchen).
**Part 3:** In two weeks we’ll define and train a neural network that combines our categorical/numerical attributes with our images, leading to better, more accurate house price prediction than the attributes or images alone.

Unlike classification (which predicts labels), regression enables us to predict continuous values. For example, classification may be able to predict one of the following values: {cheap, affordable, expensive}. Regression, on the other hand, will be able to predict an exact dollar amount, such as “The estimated price of this house is $489,121”.

In many real-world situations, such as house price prediction or stock market forecasting, applying regression rather than classification is critical to obtaining good predictions.

### Classification vs. Regression

Typically, we discuss Keras and deep learning in the context of classification — predicting a label to characterize the contents of an image or an input set of data. Regression, on the other hand, enables us to predict continuous values. Let’s again consider the task of house price prediction.

As we know, classification is used to predict a class label. For house price prediction, we may define our categorical labels as: labels = {very cheap, cheap, affordable, expensive, very expensive}. If we performed classification, our model could then learn to predict one of those five values based on a set of input features. However, those labels are just that — categories that represent a potential range of prices for the house but do nothing to represent the actual cost of the home.

In order to predict the actual cost of a home, we need to perform regression. Using regression, we can train a model to predict a continuous value. For example, while classification may only be able to predict a label, regression could say: “Based on my input data, I estimate the cost of this house to be $781,993.”

### The House Prices Dataset

The dataset we’ll be using today is from a 2016 paper, House price estimation from visual and textual features, by Ahmed and Moustafa. The dataset includes both numerical/categorical attributes along with images for 535 data points, making it an excellent dataset to study for regression and mixed data prediction.

The house dataset includes four numerical and categorical attributes:
- Number of bedrooms
- Number of bathrooms
- Area (i.e., square footage)
- Zip code

These attributes are stored on disk in CSV format. We’ll be loading these attributes from disk later in this tutorial using pandas, a popular Python package used for data analysis.

A total of four images are also provided for each house:
- Bedroom
- Bathroom
- Kitchen
- Frontal view of the house

The end goal of the houses dataset is to predict the price of the home itself. In today’s tutorial, we’ll be working with just the numerical and categorical data. Next week’s blog post will discuss working with the image data. And finally, two weeks from now we’ll combine the numerical/categorical data with the images to obtain our best performing model.

### Configuring Your Development Environment

For this 3-part series of blog posts, you’ll need to have the following packages installed:
- NumPy
- scikit-learn
- pandas
- Keras with the TensorFlow backend (CPU or GPU)
- OpenCV (for the next two blog posts in the series)

To configure your system for this series of tutorials, I recommend following either of these tutorials: Either tutorial will help you configure your system with all the necessary software for this blog post in a convenient Python virtual environment. Please note that PyImageSearch does not recommend or support Windows for CV/DL projects.

### Downloading the House Prices Dataset

Before you download the dataset, go ahead and grab the source code to this post by using the “Downloads” section. From there, unzip the file and navigate into the directory:
$ cd path/to/downloaded/zip
$ unzip keras-regression.zip
$ cd keras-regression

From there, you can download the House Prices Dataset using the following command:
$ git clone https://github.com/emanhamed/Houses-dataset

When we are ready to train our Keras regression network, you’ll then need to supply the path to the Houses-dataset directory via command line argument.

### Project Structure

Now that you have the dataset, go ahead and use the tree command with the same arguments shown below to print a directory + file listing for the project:
$ tree --dirsfirst --filelimit 10 .
├── Houses-dataset
│   ├── Houses Dataset [2141 entries]
│   └── README.md
├── pyimagesearch
│   ├── __init__.py
│   ├── datasets.py
│   └── models.py
└── mlp_regression.py
3 directories, 5 files

The dataset downloaded from GitHub now resides in the Houses-dataset/ folder. The pyimagesearch/ directory is actually a module included with the code “Downloads” where inside, you’ll find:
- datasets.py: Our script for loading the numerical/categorical data from the dataset
- models.py: Our Multi-Layer Perceptron architecture implementation

These two scripts will be reviewed today. Additionally, we’ll be reusing both datasets.py and models.py (with modifications) in the next two tutorials to keep our code organized and reusable. The regression + Keras script is contained in mlp_regression.py which we’ll be reviewing it as well.

### Loading the House Prices Dataset

Before we can train our Keras regression model, we first need to load the numerical and categorical data for the houses dataset. Open up the datasets.py file and insert the following code:
```python
# import the necessary packages
from sklearn.preprocessing import LabelBinarizer
from sklearn.preprocessing import MinMaxScaler
import pandas as pd
import numpy as np
import glob
import cv2
import os

def load_house_attributes(inputPath):
    # initialize the list of column names in the CSV file and then
    # load it using Pandas
    cols = ["bedrooms", "bathrooms", "area", "zipcode", "price"]
    df = pd.read_csv(inputPath, sep=" ", header=None, names=cols)
```
We begin by importing libraries and modules from scikit-learn, pandas, NumPy, and OpenCV. OpenCV will be used next week as we’ll be adding the ability to load images to this script.

On Line 10, we define the load_house_attributes function which accepts the path to the input dataset. Inside the function, we start off by defining the names of the columns in the CSV file (Line 13). From there, we use pandas’ function, read_csv, to load the CSV file into memory as a date frame (df) on Line 14.

Below you can see an example of our input data, including the number of bedrooms, number of bathrooms, area (i.e., square footage), zip code, code, and finally the target price our model should be trained to predict:
```
bedrooms  bathrooms  area  zipcode  price
0         4         4.0  4053    85255  869500.0
1         4         3.0  3343    36372  865200.0
2         3         4.0  3923    85266  889000.0
3         5         5.0  4022    85262  910000.0
4         3         4.0  4116    85266  971226.0
```
Let’s finish up the rest of the load_house_attributes function:
```python
# determine (1) the unique zip codes and (2) the number of data
# points with each zip code
zipcodes = df["zipcode"].value_counts().keys().tolist()
counts = df["zipcode"].value_counts().tolist()
# loop over each of the unique zip codes and their corresponding
# count
for (zipcode, count) in zip(zipcodes, counts):
    # the zip code counts for our housing dataset is *extremely*
    # unbalanced (some only having 1 or 2 houses per zip code)
    # so let's sanitize our data by removing any houses with less
    # than 25 houses per zip code
    if count < 25:
        idxs = df[df["zipcode"] == zipcode].index
        df.drop(idxs, inplace=True)
# return the data frame
return df
```
In the remaining lines, we:
- Determine the unique set of zip codes and then count the number of data points with each unique zip code (Lines 18 and 19).
- Filter out zip codes with low counts (Line 28). For some zip codes, we only have one or two data points, making it extremely challenging, if not impossible, to obtain accurate house price estimates.
- Return the data frame to the calling function (Line 33).

Now let’s create the process_house_attributes function used to preprocess our data:
```python
def process_house_attributes(df, train, test):
    # initialize the column names of the continuous data
    continuous = ["bedrooms", "bathrooms", "area"]
    # performin min-max scaling each continuous feature column to
    # the range [0, 1]
    cs = MinMaxScaler()
    trainContinuous = cs.fit_transform(train[continuous])
    testContinuous = cs.transform(test[continuous])
```
We define the function on Line 35. The process_house_attributes function accepts three parameters:
- df: Our data frame generated by pandas (the previous function helps us to drop some records from the data frame)
- train: Our training data for the House Prices Dataset
- test: Our testing data.

Then on Line 37, we define the columns of our continuous data, including bedrooms, bathrooms, and size of the home. We’ll take these values and use scikit-learn’s MinMaxScaler to scale the continuous features to the range [0, 1] (Lines 41-43).

Now we need to pre-process our categorical features, namely the zip code:
```python
# one-hot encode the zip code categorical data (by definition of
# one-hot encoing, all output features are now in the range [0, 1])
zipBinarizer = LabelBinarizer().fit(df["zipcode"])
trainCategorical = zipBinarizer.transform(train["zipcode"])
testCategorical = zipBinarizer.transform(test["zipcode"])
# construct our training and testing data points by concatenating
# the categorical features with the continuous features
trainX = np.hstack([trainCategorical, trainContinuous])
testX = np.hstack([testCategorical, testContinuous])
# return the concatenated training and testing data
return (trainX, testX)
```
First, we’ll one-hot encode the zip codes (Lines 47-49). Then we’ll concatenate the categorical features with the continuous features using NumPy’s hstack function (Lines 53 and 54), returning the resulting training and testing sets as a tuple (Line 57).

Keep in mind that now both our categorical features and continuous features are all in the range [0, 1].

### Implementing a Neural Network for Regression

Before we can train a Keras network for regression, we first need to define the architecture itself. Today we’ll be using a simple Multilayer Perceptron (MLP) as shown in Figure 5.

Open up the models.py file and insert the following code:
```python
# import the necessary packages
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model

def create_mlp(dim, regress=False):
    # define our MLP network
    model = Sequential()
    model.add(Dense(8, input_dim=dim, activation="relu"))
    model.add(Dense(4, activation="relu"))
    # check to see if the regression node should be added
    if regress:
        model.add(Dense(1, activation="linear"))
    # return our model
    return model
```
First, we’ll import all of the necessary modules from Keras (Lines 2-11). We’ll be adding a Convolutional Neural Network to this file in next week’s tutorial, hence the additional imports that aren’t utilized here today.

Let’s define the MLP architecture by writing a function to generate it called create_mlp. The function accepts two parameters:
- dim: Defines our input dimensions
- regress: A boolean defining whether or not our regression neuron should be added

We’ll go ahead and start construction our MLP with a dim-8-4 architecture (Lines 15-17). If we are performing regression, we add a Dense layer containing a single neuron with a linear activation function (Lines 20 and 21). Typically we use ReLU-based activations, but since we are performing regression we need a linear activation.

Finally, our model is returned on Line 24.

### Implementing our Keras Regression Script

It’s now time to put all the pieces together! Open up the mlp_regression.py file and insert the following code:
```python
# import the necessary packages
from tensorflow.keras.optimizers import Adam
from sklearn.model_selection import train_test_split
from pyimagesearch import datasets
from pyimagesearch import models
import numpy as np
import argparse
import locale
import os

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", type=str, required=True, help="path to input dataset of house images")
args = vars(ap.parse_args())
```
We begin by importing necessary packages, modules, and libraries. Namely, we’ll need the Adam optimizer from Keras, train_test_split from scikit-learn, and our datasets + models functions from the pyimagesearch module.

Additionally, we’ll use math features from NumPy for collecting statistics when we evaluate our model. The argparse module is for parsing command line arguments. Our script requires just one command line argument --dataset (Lines 12-15). You’ll need to provide the --dataset switch and the actual path to the dataset when you go to run the training script in your terminal.

Let’s load the house dataset attributes and construct our training and testing splits:
```python
# construct the path to the input .txt file that contains information
# on each house in the dataset and then load the dataset
print("[INFO] loading house attributes...")
inputPath = os.path.sep.join([args["dataset"], "HousesInfo.txt"])
df = datasets.load_house_attributes(inputPath)
# construct a training and testing split with 75% of the data used
# for training and the remaining 25% for evaluation
print("[INFO] constructing training/testing split...")
(train, test) = train_test_split(df, test_size=0.25, random_state=42)
```
Using our handy load_house_attributes function, and by passing the inputPath to the dataset itself, our data is loaded into memory (Lines 20 and 21). Our training (75%) and testing (25%) data is constructed via Line 26 and scikit-learn’s train_test_split method.

Let’s scale our house pricing data:
```python
# find the largest house price in the training set and use it to
# scale our house prices to the range [0, 1] (this will lead to
# better training and convergence)
maxPrice = train["price"].max()
trainY = train["price"] / maxPrice
testY = test["price"] / maxPrice
```
As stated in the comment, scaling our house prices to the range [0, 1] will allow our model to more easily train and converge. Scaling the output targets to [0, 1] will reduce the range of our output predictions (versus [0, maxPrice]) and make it not only easier but enable our model to obtain better results as well. Thus, we grab the maximum price in the training set (Line 31), and proceed to scale our training and testing data accordingly (Lines 32 and 33).

Let’s process the house attributes now:
```python
# process the house attributes data by performing min-max scaling
# on continuous features, one-hot encoding on categorical features,
# and then finally concatenating them together
print("[INFO] processing data...")
(trainX, testX) = datasets.process_house_attributes(df, train, test)
```
Recall from the datasets.py script that the process_house_attributes function:
- Pre-processes our categorical and continuous features.
- Scales our continuous features to the range [0, 1] via min-max scaling.
- One-hot encodes our categorical features.
- Concatenates the categorical and continuous features to form the final feature vector.

Now let’s go ahead and fit our MLP model to the data:
```python
# create our MLP and then compile the model using mean absolute
# percentage error as our loss, implying that we seek to minimize
# the absolute percentage difference between our price *predictions*
# and the *actual prices*
model = models.create_mlp(trainX.shape[1], regress=True)
opt = Adam(lr=1e-3, decay=1e-3 / 200)
model.compile(loss="mean_absolute_percentage_error", optimizer=opt)
# train the model
print("[INFO] training model...")
model.fit(x=trainX, y=trainY, validation_data=(testX, testY), epochs=200, batch_size=8)
```
Our model is initialized with the Adam optimizer (Lines 45 and 46) and then compiled (Line 47). Notice that we’re using mean absolute percentage error as our loss function, indicating that we seek to minimize the mean percentage difference between the predicted price and the actual price.

The actual training process is kicked off on Lines 51-53.

After training is complete, we can evaluate our model and summarize our results:
```python
# make predictions on the testing data
print("[INFO] predicting house prices...")
preds = model.predict(testX)
# compute the difference between the *predicted* house prices and the
# *actual* house prices, then compute the percentage difference and
# the absolute percentage difference
diff = preds.flatten() - testY
percentDiff = (diff / testY) * 100
absPercentDiff = np.abs(percentDiff)
# compute the mean and standard deviation of the absolute percentage
# difference
mean = np.mean(absPercentDiff)
std = np.std(absPercentDiff)
# finally, show some statistics on our model
locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
print("[INFO] avg. house price: {}, std house price: {}".format(
    locale.currency(df["price"].mean(), grouping=True),
    locale.currency(df["price"].std(), grouping=True)))
print("[INFO] mean: {:.2f}%, std: {:.2f}%".format(mean, std))
```
Line 57 instructs Keras to make predictions on our testing set. Using the predictions, we compute the:
- Difference between predicted house prices and the actual house prices (Line 62).
- Percentage difference (Line 63).
- Absolute percentage difference (Line 64).

From there, on Lines 68 and 69, we calculate the mean and standard deviation of the absolute percentage difference. The results are printed via Lines 73-76.

Regression with Keras wasn’t so tough, now was it? Let’s train the model and analyze the results!

### Keras Regression Results

To train our own Keras network for regression and house price prediction, make sure you have:
- Configured your development environment according to the guidance above.
- Used the “Downloads” section of this tutorial to download the source code.
- Downloaded the house prices dataset based on the instructions in the “The House Prices Dataset” section above.

From there, open up a terminal and supply the following command (making sure the --dataset command line argument points to where you downloaded the house prices dataset):
```
$ python mlp_regression.py --dataset Houses-dataset/Houses\ Dataset/
[INFO] loading house attributes...
[INFO] constructing training/testing split...
[INFO] processing data...
[INFO] training model...
Epoch 1/200
34/34 [==============================] - 0s 4ms/step - loss: 73.0898 - val_loss: 63.0478
Epoch 2/200
34/34 [==============================] - 0s 2ms/step - loss: 58.0629 - val_loss: 56.4558
Epoch 3/200
34/34 [==============================] - 0s 1ms/step - loss: 51.0134 - val_loss: 50.1950
Epoch 4/200
34/34 [==============================] - 0s 1ms/step - loss: 47.3431 - val_loss: 47.6673
Epoch 5/200
34/34 [==============================] - 0s 1ms/step - loss: 45.5581 - val_loss: 44.9802
Epoch 6/200
34/34 [==============================] - 0s 1ms/step - loss: 42.4403 - val_loss: 41.0660
Epoch 7/200
34/34 [==============================] - 0s 1ms/step - loss: 39.5451 - val_loss: 34.4310
Epoch 8/200
34/34 [==============================] - 0s 2ms/step - loss: 34.5027 - val_loss: 27.2138
Epoch 9/200
34/34 [==============================] - 0s 2ms/step - loss: 28.4326 - val_loss: 25.1955
Epoch 10/200
34/34 [==============================] - 0s 2ms/step - loss: 28.3634 - val_loss: 25.7194
...
Epoch 195/200
34/34 [==============================] - 0s 2ms/step - loss: 20.3496 - val_loss: 22.2558
Epoch 196/200
34/34 [==============================] - 0s 2ms/step - loss: 20.4404 - val_loss: 22.3071
Epoch 197/200
34/34 [==============================] - 0s 2ms/step - loss: 20.0506 - val_loss: 21.8648
Epoch 198/200
34/34 [==============================] - 0s 2ms/step - loss: 20.6169 - val_loss: 21.5130
Epoch 199/200
34/34 [==============================] - 0s 2ms/step - loss: 19.9067 - val_loss: 21.5018
Epoch 200/200
34/34 [==============================] - 0s 2ms/step - loss: 19.9570 - val_loss: 22.7063
[INFO] predicting house prices...
[INFO] avg. house price: $533,388.27, std house price: $493,403.08
[INFO] mean: 22.71%, std: 18.26%
```
As you can see from our output, our initial mean absolute percentage error starts off as high as 73% and then quickly drops to under 30%. By the time we finish training, we can see our network starting to overfit a bit. Our training loss is as low as ~20%; however, our validation loss is at ~23%.

Computing our final mean absolute percentage error, we obtain a final value of 22.71%. What does this value mean? Our final mean absolute percentage error implies that, on average, our network will be ~23% off in its house price predictions with a standard deviation of ~18%.

### Limitations of the House Price Dataset

Being 22% off in a house price prediction is a good start but is certainly not the type of accuracy we are looking for. That said, this prediction accuracy can also be seen as a limitation of the house price dataset itself.

Keep in mind that the dataset only includes four attributes:
- Number of bedrooms
- Number of bathrooms
- Area (i.e., square footage)
- Zip code

Most other house price datasets include many more attributes. For example, the Boston House Prices Dataset includes a total of fourteen attributes which can be leveraged for house price prediction (although that dataset does have some racial discrimination). The Ames House Dataset includes over 79 different attributes which can be used to train regression models.

When you think about it, the fact that we are able to even obtain 26% mean absolute percentage error without the knowledge of an expert real estate agent is fairly reasonable given:
- There are only 535 total houses in the dataset (we only used 362 total houses for the purpose of this guide).
- We only have four attributes to train our regression model on.
- The attributes themselves, while important in describing the home itself, do little to characterize the area surrounding the house.
- The house prices are incredibly varied with a mean of $533K and a standard deviation of $493K (based on our filtered dataset of 362 homes).

With all that said, learning how to perform regression with Keras is an important skill! In the next two posts in this series, I’ll be showing you how to:
- Leverage the images provided with the house price dataset to train a CNN on them.
- Combine our numerical/categorical data with the house images, leading to a model that outperforms all of our previous Keras regression experiments.

### What's next? We recommend PyImageSearch University.

Course information:
84 total classes • 114+ hours of on-demand code walkthrough videos • Last updated: February 2024

★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled

I strongly believe that if you had the right teacher, you could master computer vision and deep learning. Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?

That’s not the case. All you need to master computer vision and deep learning is for someone to explain things to you in simple, intuitive terms. And that’s exactly what I do. My mission is to change education and how complex Artificial Intelligence topics are taught.

If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to successfully and confidently apply computer vision to your work, research, and projects. Join me in computer vision mastery.

Inside PyImageSearch University, you'll find:
- 84 courses on essential computer vision, deep learning, and OpenCV topics
- 84 Certificates of Completion
- 114+ hours of on-demand video
- Brand new courses released, ensuring you can keep up with state-of-the-art techniques regularly
- Pre-configured Jupyter Notebooks in Google Colab
- Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
- Access to centralized code repos for all 536+ tutorials on PyImageSearch
- Easy one-click downloads for code, datasets, pre-trained models, etc.
- Access on mobile, laptop, desktop, etc.

## Summary

In this tutorial, you learned how to use the Keras deep learning library for regression. Specifically, we used Keras and regression to predict the price of houses based on four numerical and categorical attributes:
- Number of bedrooms
- Number of bathrooms
- Area (i.e., square footage)
- Zip code

Overall, our neural network obtained a mean absolute percentage error of 22.71%, implying that, on average, our house price predictions will be off by 22.71%. That raises the questions:
- How can we better our house price prediction accuracy?
- What if we leveraged images for each house? Would that improve accuracy?
- Is there some way to combine both our categorical/numerical attributes with our image data?

To answer these questions, you’ll need to stay tuned for the remaining two tutorials in this Keras regression series.

To download the source code to this post (and be notified when the next tutorial is published here on PyImageSearch), just enter your email address in the form below.


In coding theory, a set of strings has the property of unique decodability if any concatenation of strings from the set can be decoded uniquely. For example, the set S1 = { "ab", "abba", "b" } does not have this property because the two sequences [ "ab", "b", "ab" ] and [ "abba", "b" ] both concatenate to "abbab". On the other hand, the set S2 = { "a", "ab", "abb" } does have this property.

One way to ensure unique decodability is to append delimiters to the code words. For instance, if we delimit the code words in S1, it becomes { "(ab)", "(abba)", "(b)" }, and the two problem sequences are now distinguishable. Alternatively, we can use a prefix code, where no code word is a prefix of another. Adding delimiters to a code turns it into a prefix code, but not all prefix codes have delimiters.

A prefix code can be decoded using a tree, where the code words are arranged at the leaves of the tree. To decode a concatenation of code words, we can scan the symbols one at a time, walking the tree, until we reach a leaf, which tells us which code word we just saw. This is the basis of Huffman coding.

However, not all uniquely-decodable codes are prefix codes. For example, a suffix code is uniquely-decodable but may not be a prefix code. Moreover, codes can be uniquely-decodable without being either prefix or suffix codes.

To determine whether a code is uniquely-decodable, we can use an algorithm that tabulates solutions to Xs = Y, where X and Y are sequences of code words, for various strings s. If s is empty, we win. We start by looking for pairs of code words with one being a prefix of the other and maintain a queue of s-values to investigate.

The algorithm works by adding s' to the queue when s begins with a code word or is a prefix of a code word. If we encounter a queue item that we have seen before, we can discard it to prevent going in circles. If the next queue item is the empty string, we have proved that the code is not uniquely-decodable. If the queue is empty, we have investigated all possibilities and the code is uniquely-decodable.

The implementation of the algorithm can use a hash to track which strings s have appeared in the queue already, along with two sequences of code words, P and Q, such that Ps = Q. When s begins with a code word, we add s' to the hash with the two sequences [P, c] and Q. When s is a prefix of a code word, we add s' to the hash with the two sequences Q and [P, c], reversing the order of the sequences to maintain the Ps = Q property.

The worst-case running time of the algorithm is O(nk), where k is the number of code words and n is their total length. However, in practice, the algorithm always seems to complete very quickly. The algorithm is known as the Sardinas-Patterson Algorithm.

Example: Is { "ab", "baab", "babb", "bbb", "bbba" } uniquely-decodable? If not, find a pair of sequences that concatenate to the same string.

Research question: What's the worst-case running time of the algorithm in practice?

Project to do: Reimplement the algorithm in Haskell and compare it with the Perl implementation.


## Floating Point Numbers

Floating point numbers have two smallest values: `min` and `min * epsilon`. `min` is the smallest normalized float, while `min * epsilon` is the smallest subnormal float. In Python, `sys.float_info.min` is approximately 2.2250738585072014e-308, and `sys.float_info.min * sys.float_info.epsilon` is approximately 5e-324.

### Normalized and Subnormal Floats

Normalized floats have full precision, while subnormal floats lose precision. Subnormal numbers cover the range between 0 and `min`, but are much slower to work with, up to 100x slower than normalized floats.

### Machine Epsilon

Machine epsilon, represented by `sys.float_info.epsilon`, is the smallest positive float value that is greater than zero. It is used to compensate for rounding errors in numerical code. Machine epsilon equals the smallest number such that `(1.0 + machine epsilon) != 1.0`.

### Example Code

```python
import sys
print(sys.float_info.min)  # approximately 2.2250738585072014e-308
print(sys.float_info.min * sys.float_info.epsilon)  # approximately 5e-324
print((1 + (sys.float_info.epsilon / 2)) == 1)  # True
print((1 + sys.float_info.epsilon) == (1 + (sys.float_info.epsilon * (2. / 3))))  # True
```

### Signed Zero

In Python, zero can be positive (+0) or negative (-0). Although a test for equality on +0 and -0 will return true, they can lead to different results when used in subsequent calculations.

### Infinity

Python has built-in support for infinity using `math.isinf()`, `np.isposinf()`, and `np.isneginf()`. Infinite values can be generated using `float('inf')` and `float('-inf')`.

### NaN (Not a Number)

NaN can be generated using `float('nan')` and can be tested using `np.isnan()`. There are two types of NaN: signalling NaN (SNaN) and quiet NaN (QNaN).

### Example Code

```python
import numpy as np
import math
print(np.isposinf(float('inf')))  # True
print(np.isneginf(float('-inf')))  # True
print(np.isnan(float('nan')))  # True
print(np.isnan(math.sqrt(-1.0)))  # raises a math domain error
```

### Relative Error and Machine Epsilon

The relative error corresponding to 0.5 ulp (units in the last place) can vary by a factor, known as the wobble. Machine epsilon is the maximum relative error when a real number is rounded to the closest floating-point number.

### Syntax

`Number.EPSILON` represents the smallest positive float value that is greater than zero.

### Output

```
2.2204460492503130808472633361816E-16
false
true
```


RESONATE PARALLEL NETWORKS REVIEWED:

A combination of inductance and capacitance connected in parallel results in a high resistance at a specific frequency, creating a special resistor designed to work at a narrow band of frequencies. Other frequencies exhibit low resistance.

TRI-BAND ANTENNA ELEMENT TRAP EXAMPLE:

In a Tri-band 10, 15, and 20 meter beam, the 21 MHz energy only uses the length of the element to the 21 MHz trap, situated 1/4 wavelength from the boom. The same electric circuit is present on 10 meters, while the 14 MHz signal perceives the 21 and 28 MHz traps as closed switches. The 20 meter signal uses the whole length of the element.

TYPICAL TRAP FOR 20-15-10-METER BEAM

The parallel tuned traps used in multi-band beams and wire dipoles consist of a capacitor made by inserting one aluminum tube inside another with an insulating sleeve in between. The capacitance should be around 25 pf for the 15 and 10 meter bands when the tubes overlap about 5 inches. The coil is air wound from one tube to the other, with a diameter and length of about 3 inches. The number of turns is 7 for 15 meters and 5 for 10 meters, using approximately number 8 aluminum wire. Final tuning is done with a grid dip meter, adjusting the coil and capacitor to resonate the network at the lower edge of the designated band.

TYPICAL TRAP FOR 20-15-10-METER WIRE DIPOLE

The same values of inductance and capacitance apply. The voltage rating of the capacitor should be in the 2 to 3 KV range. For higher power, a higher KV rating is required. When identical capacitors are installed in series, the total value of capacitance is obtained by dividing the value of one capacitor by the total number of capacitors in the string.


This resource includes 10 real-world AREA word problems that require students to solve and explain using problem-solving strategies. Each graphic organizer presents a word problem, and students must organize the given information, solve, justify their work, and explain their solution. The answer key provides correct solutions and sample work.

The activity can be used in various settings, including pair-shares, homework, stations, classwork, early finishers, and assessment prep. It covers the following topics:
✔ Area of Parallelograms
✔ Area of Triangles
✔ Area of Trapezoids
✔ Area on the Coordinate Plane
✔ Area of Composite Figures

Additionally, a similar resource is available for Volume & Surface Area of Prisms, which includes 10 real-world word problems. Students must solve and explain these problems using problem-solving strategies, organizing the given information, solving, justifying their work, and explaining their solution. This resource covers:
✔ Volume of Rectangular Prisms
✔ Volume of Triangular Prisms
✔ Surface Area of Rectangular Prisms
✔ Surface Area of Triangular Prisms

Both resources are aligned with Common Core standards 6.G.1, 6.G.2, 6.G.3, and 6.G.4, and can be used in various instructional settings.


To solve the division problem of 6.3 divided by 0.25, we can rewrite it to make the division easier. Instead of dividing by 25 hundredths (0.25), we can divide by 25, a whole number. To do this, we multiply 0.25 by 100 (10 twice) to get 25. Since we're changing the divisor, we must also change the dividend in the same way.

6.3 can be written as 6.30, and when we move the decimal point two places to the right (multiplying by 100), it becomes 630. So, 6.3 divided by 0.25 is the same as 630 divided by 25.

Now, let's perform the division: 630 divided by 25.

We start by dividing 25 into 630. 25 goes into 63 two times (2 * 25 = 50), with a remainder of 13. Bringing down the next zero, we get 130. 25 goes into 130 five times (5 * 25 = 125), with a remainder of 5. Bringing down another zero, we get 50. 25 goes into 50 two times (2 * 25 = 50), with no remainder.

So, 630 divided by 25 equals 25.2. Since our original problem was 6.3 divided by 0.25, and we multiplied both the dividend and divisor by 100 to simplify, the answer to the original problem is also 25.2.


# Solving Recurrence Equation for $n$

The given recurrence equation is $t_n = 2.5t_{n-1} - 1.5t_{n-4}$, for $n \geq 5$. Initial conditions are $t_1 = 5$, $t_2 = 10.5$, $t_3 = 26.25$, and $t_4 = 62.625$. The goal is to find $n$ when $t_n = 13 \times 10^{10}$.


To memorize the graphs of circular functions such as sin, cos, tan, sec, csc, and cot, focus on key characteristics. Sin and cos have similar shapes, but cos has a y-intercept of 1. Tan's graph can be visualized by imagining a heart monitor, with intercepts and asymptotes being helpful for memorization. Cot's graph is essentially tan's graph flipped.

For sin and cos, remember the general shape, y-intercept, and direction. Tan may require memorization, but focusing on intercepts and asymptotes can aid in recall. Once sin, cos, and tan are understood, their inverses (sec, csc, and cot) can be determined as 1/f(x).

To graph sin, start at sin(0) = 0 and imagine moving around the circle. Sine increases until pi/2, decreases to 0 at pi, goes negative until 3pi/2, and returns to 0 at 2pi. Drawing this process can help solidify the graph in memory. Additionally, plugging in numbers to generate y-values and understanding amplitudes can further assist in graphing these functions.


The shoelace formula was introduced as a new concept. However, its implementation is experiencing issues.

The provided code works correctly with a 4-point plane but fails with a 16-point plane. The code is as follows:
```
import c4d
x = []
y = []
def main():
    baseVector = op.GetAllPoints()
    for vector in baseVector:
        x.append(vector[0])
        y.append(vector[1])
def polygonArea(X, Y, n):
    area = 0.0
    j = n - 1
    for i in range(0,n):
        area += (X[j] + X[i]) * (Y[j] - Y[i])
        j = i
    return int(abs(area / 2.0))
if __name__=='__main__':
    main()
    print(polygonArea(x, y, 16))
```
A test file is available at https://www.dropbox.com/s/6qfhy9yw3l3xdil/c4d081_area_irregular_shape.c4d?dl=0, containing both 4-point and 16-point planes. The expected area for the square shape is 160,000 cm2.


An Eigencircle Applet
======================
Graham Farr, Faculty of IT, Monash University

Contents
--------
1. Introduction to Eigencircles
2. The Applet
3. Guide to the Eigencircle Applet
3.1. Getting Started
3.2. Edit Options
3.3. Display Options
3.4. Matrix Information
3.5. Buttons
References

Introduction to Eigencircles
----------------------------
The eigencircle of a 2x2 matrix is a special circle based on the matrix that generalizes the set of eigenvalues of the matrix. It can be used to give simple geometric illustrations of many properties of the matrix. An eigenvalue of a 2x2 matrix is a number λ such that:

(
 a  b
 )
 (
 x
 )
 =
 λ
 (
 x
 )

c  d
 y  y

for some x, y not both 0. We can rewrite this equation as:

(
 a  b
 )
 (
 x
 )
 =
 (
 λ  0
 )
 (
 x
 )

c  d
 y
 0  λ
 y

Our generalization is inspired by a well-known way of representing complex numbers as real 2x2 matrices. Let λ + μi be complex (where λ and μ are real). Then the correspondence:

(
 λ  μ
 )
 (
 x
 )
 =
 (
 λ  μ
 )
 (
 x
 )

0  λ
 y
 μ  λ
 y

is a field isomorphism that represents any complex number by a real 2x2 matrix of appropriate form. We call a pair of real numbers (λ,μ) that satisfy this equation an eigenpair. The set of eigenpairs describes a circle in the real λ,μ-plane, and it is this circle which we call the eigencircle.

The Applet
----------
To launch the eigencircle applet, press the button below. You must have Java installed to run the applet. If you are not sure whether your web browser can run Java applets, click here to test it.

Guide to the Eigencircle Applet
-------------------------------
### 3.1. Getting Started
The applet initially appears as a button sitting in this web page. The purpose of this button is to launch eigencircle windows. Each such window allows you to enter a 2x2 matrix, view its eigencircle, and experiment interactively. When an eigencircle window first starts, you will see a large blank area on the left and various buttons and fields on the right.

### 3.2. Edit Options
You choose what to edit by clicking one of the five radio buttons in the top right of the window:
* Matrix: enables you to type in or modify the matrix entries.
* Eigencircle Centre: enables you to change the coordinates of the eigencircle's centre.
* Eigencircle Radius: enables you to change the eigencircle's radius.
* Vary a Matrix Element, Fix Eigencircle: enables you to vary any single matrix element while keeping the eigencircle fixed.
* Vary Matrix/Circle, Fix Eigenvalues: enables you to vary anything at all (matrix element, eigencircle centre, or eigencircle radius) while keeping the eigenvalues fixed.

### 3.3. Display Options
You have a number of choices as to what is, or is not, displayed in the graph. These choices are made by clicking the checkboxes under the heading DISPLAY OPTIONS:
* Special Rectangle: displays the rectangle formed by the four points with λ-coordinates a or d and μ-coordinates b or c.
* Determinant: displays the line segment and right-angle triangle related to the determinant.
* Eigenvalues: displays lines whose lengths are the eigenvalues.
* Eigenvectors: displays eigenvectors as grey vectors (only if the eigenvalues are real).
* Scales on Axes: provides scales on the axes (can be removed).

### 3.4. Matrix Information
Further down on the right, there are fields that display information about the matrix: its determinant, trace, eigenvalues, and eigenvectors (if the eigenvalues are real). The equation of the eigencircle is also given.

### 3.5. Buttons
There are four buttons at the very right edge of the window:
* Calculate: calculates the eigencircle and matrix information from the current 2x2 matrix.
* Reframe: reframes the current eigencircle without recalculating it.
* Previous Matrix: takes you back to the previous matrix.
* Quit: makes the eigencircle window quit.

References
----------
[1] M J Englefield and G E Farr, Eigencircles of 2x2 matrices, Mathematics Magazine 79 (October 2006) 281-289.
[2] M J Englefield and G E Farr, Eigencircles and associated surfaces, submitted, 2009.