text:
[This article was first published on R Programming – DataScience+, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

## Motivation

I have had a lot of fun exploring The US cities’ Crime data via their Open Data portals. Because Toronto’s crime data was simply not available.

Not until the summer of this year, Toronto police launch a public safety data portal to increase transparency between the public and officers. I recently have had the chance to explore Toronto’s crimes via Toronto Police Service Public Safety Data Portal. I am particularly interested in Major Crime Indicators (MCI) 2016 which contains a tabular list of 32, 612 reports in 2016 (The only year that the data were made available).

Let’s take a look at the data using R and see if there’s anything interesting.

library(ggplot2)
library(ggthemes)
library(dplyr)
library(viridis)
library(tidyr)
library(cluster)
library(ggmap)
library(maps)

After a little bit of exploration, I found that there were many duplicated event_unique_id. Let’s drop them.

toronto <- read.csv('toronto_crime.csv')
toronto <- subset(toronto, !duplicated(toronto$event_unique_id)) unique(toronto$occurrenceyear)
unique(toronto$reportedyear) > unique(toronto$occurrenceyear)
[1] 2016 2015 2014 2012 2010 2013 2011 2003 2007 2008 2006 2002 2001   NA 2005
[16] 2009 2000
> unique(toronto$reportedyear) [1] 2016  Find anything interesting? The occurrence year ranged from 2000 to 2016, but report year is only 2016. This means people came to police to report incidents happened 16 years ago. Let’s have a look how many late reported incidents in our data. year_group <- group_by(toronto, occurrenceyear) crime_by_year <- summarise(year_group, n = n()) crime_by_year # A tibble: 17 x 2 occurrenceyear n 1 2000 2 2 2001 2 3 2002 3 4 2003 2 5 2005 1 6 2006 1 7 2007 5 8 2008 1 9 2009 1 10 2010 10 11 2011 3 12 2012 8 13 2013 21 14 2014 37 15 2015 341 16 2016 27705 17 NA 4  2 incidents occurred in 2000, 2 occurred in 2001 and so on. The vast majority of occurrences happened in 2016. So we are going to keep 2016 only. And I am also removing all the columns we do not need and four rows with missing values. drops <- c("X", "Y", "Index_", "ucr_code", "ucr_ext", "reporteddate", "reportedmonth", "reportedday", "reporteddayofyear", "reporteddayofweek", "reportedhour", "occurrencedayofyear", "reportedyear", "Division", "Hood_ID", "FID") toronto <- toronto[, !(names(toronto) %in% drops)] toronto <- toronto[toronto$occurrenceyear == 2016, ]
toronto <- toronto[complete.cases(toronto), ]

## Explore

### What are the major crimes in 2016?

indicator_group <- group_by(toronto, MCI)
crime_by_indicator <- summarise(indicator_group, n=n())
crime_by_indicator <- crime_by_indicator[order(crime_by_indicator$n, decreasing = TRUE),] ggplot(aes(x = reorder(MCI, n), y = n), data = crime_by_indicator) + geom_bar(stat = 'identity', width = 0.5) + geom_text(aes(label = n), stat = 'identity', data = crime_by_indicator, hjust = -0.1, size = 3.5) + coord_flip() + xlab('Major Crime Indicators') + ylab('Number of Occurrences') + ggtitle('Major Crime Indicators Toronto 2016') + theme_bw() + theme(plot.title = element_text(size = 16), axis.title = element_text(size = 12, face = "bold"))  Gives this plot: Assault is the most prevalent form of violent crime in Toronto. What is assault? In criminal and civil law, assault is an attempt to initiate harmful or offensive contact with a person, or a threat to do so. ### What are the different types of assault? Which type is the worst? assault <- toronto[toronto$MCI == 'Assault', ]
assault_group <- group_by(assault, offence)
assault_by_offence <- summarise(assault_group, n=n())
assault_by_offence <- assault_by_offence[order(assault_by_offence$n, decreasing = TRUE), ] ggplot(aes(x = reorder(offence, n), y = n), data = assault_by_offence) + geom_bar(stat = 'identity', width = 0.6) + geom_text(aes(label = n), stat = 'identity', data = assault_by_offence, hjust = -0.1, size = 3) + coord_flip() + xlab('Types of Assault') + ylab('Number of Occurrences') + ggtitle('Assault Crime Toronto 2016') + theme_bw() + theme(plot.title = element_text(size = 16), axis.title = element_text(size = 12, face = "bold"))  Gives this plot: Not much information here, the top assault category is … assault. I eventually learned different types of assault through Attorneys.com. ### Let’s look at the top offences then offence_group <- group_by(toronto, offence) crime_by_offence <- summarise(offence_group, n=n()) crime_by_offence <- crime_by_offence[order(crime_by_offence$n, decreasing = TRUE), ]
ggplot(aes(x = reorder(offence, n), y = n), data = crime_by_offence) +
geom_bar(stat = 'identity', width = 0.7) +
geom_text(aes(label = n), stat = 'identity', data = crime_by_offence, hjust = -0.1, size = 2) +
coord_flip() +
xlab('Types of Offence') +
ylab('Number of Occurrences') +
ggtitle('Offence Types Toronto 2016') +
theme_bw() +
theme(plot.title = element_text(size = 16),
axis.title = element_text(size = 12, face = "bold"))

Gives this plot:

Assault being the most common offence followed by Break and Enter. According to Wikibooks, the most typical form of break and enter is a break into a commercial or private residence in order to steal property. This indicates that break and enter more likely to occur when there is no one at home or office.

### How about crime by time of the day?

hour_group <- group_by(toronto, occurrencehour)
crime_hour <- summarise(hour_group, n=n())
ggplot(aes(x=occurrencehour, y=n), data = crime_hour) + geom_line(size = 2.5, alpha = 0.7, color = "mediumseagreen", group=1) +
geom_point(size = 0.5) +
ggtitle('Total Crimes by Hour of Day in Toronto 2016') +
ylab('Number of Occurrences') +
xlab('Hour(24-hour clock)') +
theme_bw() +
theme(plot.title = element_text(size = 16),
axis.title = element_text(size = 12, face = "bold"))

Gives this plot:

The worst hour is around the midnight, another peak time is around the noon, then again at around 8pm.

### Okay, but what types of crime are most frequent at each hour?

hour_crime_group <- group_by(toronto, occurrencehour, MCI)
hour_crime <- summarise(hour_crime_group, n=n())
ggplot(aes(x=occurrencehour, y=n, color=MCI), data =hour_crime) +
geom_line(size=1.5) +
ggtitle('Crime Types by Hour of Day in Toronto 2016') +
ylab('Number of Occurrences') +
xlab('Hour(24-hour clock)') +
theme_bw() +
theme(plot.title = element_text(size = 16),
axis.title = element_text(size = 12, face = "bold"))

Gives this plot:

Assaults are the top crimes almost all the time, they happened more often from the late mornings till nights than the early mornings. On the other hand, break and enter happened more often in the mornings and at around the midnight (when no one at home or office) . Robberies and auto thefts are more likely to happen in the late evenings till the nights. They all make sense.

### Where are those crimes most likely to occur in Toronto?

location_group <- group_by(toronto, Neighbourhood)
crime_by_location <- summarise(location_group, n=n())
crime_by_location <- crime_by_location[order(crime_by_location$n, decreasing = TRUE), ] crime_by_location_top20 <- head(crime_by_location, 20) ggplot(aes(x = reorder(Neighbourhood, n), y = n), data = crime_by_location_top20) + geom_bar(stat = 'identity', width = 0.6) + geom_text(aes(label = n), stat = 'identity', data = crime_by_location_top20, hjust = -0.1, size = 3) + coord_flip() + xlab('Neighbourhoods') + ylab('Number of Occurrences') + ggtitle('Neighbourhoods with Most Crimes - Top 20') + theme_bw() + theme(plot.title = element_text(size = 16), axis.title = element_text(size = 12, face = "bold"))  Gives this plot: The most dangerous neighbourhood is … Waterfront. The sprawling downtown catch-all includes not only the densely packed condo but also the boozy circus that is the entertainment district. The result: a staggering number of violent crimes and arsons. ### Let’s find out neighbourhoods vs. top offence types offence_location_group <- group_by(toronto, Neighbourhood, offence) offence_type_by_location <- summarise(offence_location_group, n=n()) offence_type_by_location <- offence_type_by_location[order(offence_type_by_location$n, decreasing = TRUE), ]
offence_type_by_location_top20 <- head(offence_type_by_location, 20)
ggplot(aes(x = Neighbourhood, y=n, fill = offence), data=offence_type_by_location_top20) +
geom_bar(stat = 'identity', position = position_dodge(), width = 0.8) +
xlab('Neighbourhood') +
ylab('Number of Occurrence') +
ggtitle('Offence Type vs. Neighbourhood Toronto 2016') + theme_bw() +
theme(plot.title = element_text(size = 16),
axis.title = element_text(size = 12, face = "bold"),
axis.text.x = element_text(angle = 90, hjust = 1, vjust = .4))

Gives this plot:

I did not expect something like this. It is not pretty. However, it did tell us that besides assaults, Church-Yonge Corridor and Waterfront had the most break and enter(Don’t move there!). West Humber-Clairville had the most vehicle stolen crimes(Don’t park your car there!).

### Let’s try something different

crime_count % group_by(occurrencemonth, MCI) %>% summarise(Total = n())
crime_count$occurrencemonth <- ordered(crime_count$occurrencemonth, levels = c('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'))
ggplot(crime_count, aes(occurrencemonth, MCI, fill = Total)) +
geom_tile(size = 1, color = "white") +
scale_fill_viridis()  +
geom_text(aes(label=Total), color='white') +
ggtitle("Major Crime Indicators by Month 2016") +
xlab('Month') +
theme(plot.title = element_text(size = 16),
axis.title = element_text(size = 12, face = "bold"))

Gives this plot:

Much better!

Assault is the most common crime every month of the year with no exception. It appears that there were a little bit more assault incidents in May than the other months last year.

day_count % group_by(occurrencedayofweek, MCI) %>% summarise(Total = n())
ggplot(day_count, aes(occurrencedayofweek, MCI, fill = Total)) +
geom_tile(size = 1, color = "white") +
scale_fill_viridis()  +
geom_text(aes(label=Total), color='white') +
ggtitle("Major Crime Indicators by Day of Week 2016") +
xlab('Day of Week') +
theme(plot.title = element_text(size = 16),
axis.title = element_text(size = 12, face = "bold"))

Gives this plot:

Saturdays and Sundays had more assaults than any other days, and had less theft over than any other days. Auto thieves are busy almost every day of the week equally.
I was expecting to find seasonal crime patterns such as temperature changes and daylight hours might be associated with crime throughout the year, or the beginning and end of the school year, are associated with variations in crime throughout the year. But this one-year’s worth of data is not enough to address my above concerns. I hope Toronto Police service will release more data via its open data portal in the soonest future.

### Homicide

homicide <- read.csv('homicide.csv', stringsAsFactors = F)
homicide$Occurrence_Date <- as.Date(homicide$Occurrence_Date)
year_group <- group_by(homicide, Occurrence_year, Homicide_Type)
homicide_by_year <- summarise(year_group, n=n())
ggplot(aes(x = Occurrence_year, y=n, fill = Homicide_Type), data=homicide_by_year) +
geom_bar(stat = 'identity', position = position_dodge(), width = 0.8) +
xlab('Year') +
ylab('Number of Homicides') +
ggtitle('Homicide 2004-2016') + theme_bw() +
theme(plot.title = element_text(size = 16),
axis.title = element_text(size = 12, face = "bold"))

Gives this plot:

2005 is Toronto’s “Year of Gun”. Eleven years later in 2016, Toronto was experiencing another spike in gun-related homicide.

homicide$month <- format(as.Date(homicide$Occurrence_Date) , "%B")
homicide_count % group_by(Occurrence_year, month) %>% summarise(Total = n())
homicide_count$month <- ordered(homicide_count$month, levels = c('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'))
ggplot(homicide_count, aes(Occurrence_year, month, fill = Total)) +
geom_tile(size = 1, color = "white") +
scale_fill_viridis()  +
geom_text(aes(label=Total), color='white') +
ggtitle("Homicides in Toronto (2004-2016)") +
xlab('Year') +
theme(plot.title = element_text(size = 16),
axis.title = element_text(size = 12, face = "bold"))

Gives this plot:

It is worrisome to see that there is a significant increase in the total number of homicides in Toronto in 2016 compared to 2015. I hope we will have a better 2017. However, when I read that Toronto ranked safest city in North America by the Economist, I felt much safer.

## K-Means Clustering

K-Means is one of the most popular “clustering” algorithms. It is the process of partitioning a group of data points into a small number of clusters. As in our crime data, we measure the number of assaults and other indicators, and neighbourhoods with high number of assaults will be grouped together. The goal of K-Means clustering is to assign a cluster to each data point (neighbourhood). Thus we first partition datapoints (neighbourhoods) into k clusters in which each neighbourhood belongs to the cluster with the nearest mean, serving as a prototype of the cluster.
As one of the unsupervised learning algorithms,we use K-Mean to build models that help us understand our data better. It enables us to learn groupings of unlabeled data points.

### To do clustering analysis, our data has to look like this:

by_groups <- group_by(toronto, MCI, Neighbourhood)
groups <- summarise(by_groups, n=n())
groups <- groups[c("Neighbourhood", "MCI", "n")]
groups_wide <- spread(groups, key = MCI, value = n)

Gives this table:

### The fist column — qualitative data should be removed from the analysis

z <- groups_wide[, -c(1,1)]

### The data cannot have any missing values

z <- z[complete.cases(z), ]

### The data must be scaled for comparison

m <- apply(z, 2, mean)
s <- apply(z, 2, sd)
z <- scale(z, m, s)

### Determine the number of clusters

wss <- (nrow(z)-1) * sum(apply(z, 2, var))
clusplot(z1, kc$cluster, color=TRUE, shade=F, labels=0, lines=0, main='k-Means Cluster Analysis')  Gives this plot: It appears that our choice of number of clusters is good, and we have little noise. ## Hierarchical Clustering For the hierarchical clustering methods, the dendrogram is the main graphical tool for getting insight into a cluster solution. z2 <- data.frame(z) distance <- dist(z2) hc <- hclust(distance)  Now that we’ve got a cluster solution. Let’s examine the results. plot(hc, labels = groups_wide$Neighbourhood, main='Cluster Dendrogram', cex=0.65)

Gives this plot:

If we choose any height along the y-axis of the dendrogram, and move across the dendrogram counting the number of lines that we cross, each line represents a cluster. For example, if we look at a height of 10, and move across the x-axis at that height, we’ll cross two lines. That defines a two-cluster solution; by following the line down through all its branches, we can see the names of the neighbourhoods that are included in these two clusters. Looking at the dendrogram for the Toronto’s crimes data, we can see our datapoins are very imbalanced. From the top of the tree, there are two distinct groups; one group consists of brunches with brunches and more brunches, while another group only consists few neighbourhoods, and we can see these neighbourhoods are Toronto’s most dangerous neighbourhoods. However, I want to try many different groupings at once to start investigating.

counts = sapply(2:6,function(ncl)table(cutree(hc,ncl)))
names(counts) = 2:6
counts
> counts
$2 1 2 128 3$3

1   2   3
128   2   1

$4 1 2 3 4 121 7 2 1$5

1   2   3   4   5
121   5   2   2   1

$6 1 2 3 4 5 6 112 5 2 9 2 1  Interpretation: * With 2-cluster solution, we have 128 neighbourhoods in cluster 1, 3 neighbourhoods in cluster 2. * With 3-cluster solution, we have 128 neighbourhoods in cluster 1, 2 neighbourhoods in cluster 2, and 1 neighbourhood in cluster 3. And so on until 6-cluster solution. In practice, we’d like a solution where there aren’t too many clusters with just few observations, because it may make it difficult to interpret our results. For this exercise, I want to stick with 3-cluster solution, see what results I will obtain. member <- cutree(hc, 3) aggregate(z, list(member), mean) aggregate(z, list(member), mean) Group.1 Assault Auto Theft Break and Enter Robbery Theft Over 1 1 -0.09969023 -0.08067526 -0.09425688 -0.09349632 -0.1042508 2 2 5.57040267 0.57693723 4.67333848 4.14398508 5.0024522 3 3 1.61954364 9.17255898 2.71820403 3.67955938 3.3392003  In cluster 1, all the crime indicators are on the negative side, cluster 1 has a significant distinction on each variable compare with cluster 2 and cluster 3. Cluster 2 is higher in most of the crime indicators than cluster 3 except Auto Theft. plot(silhouette(cutree(hc, 3), distance))  Gives this plot: The silhouette width value for cluster 3 is zero. The silhouette plot indicates that we really do not need the third cluster, The vast majority of neighbourhoods belong to the first cluster, and 2-cluster will be our solution. ## Making a Map of Toronto’s Crimes There are many packages for plotting and manipulating spatial data in R. I am going to use ggmap to produce a simple and easy map of Toronto’ crimes. lat <- toronto$Lat
lon <- toronto$Long crimes <- toronto$MCI
to_map <- data.frame(crimes, lat, lon)
colnames(to_map) <- c('crimes', 'lat', 'lon')
sbbox <- make_bbox(lon = toronto$Long, lat = toronto$Lat, f = 0.01)
my_map <- get_map(location = sbbox, maptype = "roadmap", scale = 2, color="bw", zoom = 10)
ggmap(my_map) +
geom_point(data=to_map, aes(x = lon, y = lat, color = "#27AE60"),
size = 0.5, alpha = 0.03) +
xlab('Longitude') +
ylab('Latitude') +
ggtitle('Location of Major Crime Indicators Toronto 2016') +
guides(color=FALSE)

Gives this map:

It’s clear to see where the major crimes in the city occur. A large concentration in the Waterfront area, South of North York is more peaceful than any other areas. However, point-stacking is not helpful when comparing high-density areas, so let’s optimize this visualization.

ggmap(my_map) +
geom_point(data=to_map, aes(x = lon, y = lat, color = "#27AE60"),
size = 0.5, alpha = 0.05) +
xlab('Longitude') +
ylab('Latitude') +
ggtitle('Location of Major Crime Indicators Toronto 2016') +
guides(color=FALSE) +
facet_wrap(~ crimes, nrow = 2)

Gives this map:

This is certainly more interesting and prettier. Some crimes, such as Assaults, and Break and Enter occur all over the city, with concentration in the Waterfront areas. Other crimes, such as Auto Theft has a little more points in the west side than the east side. Robbery and Theft Over primarily have clusters in the Waterfront areas.

## Summary

Not many more questions can be answered by looking at the data of Toronto Major crimes Indicators. But that’s okay. There’s certainly other interesting things to do with this data, such as creating a dashboard at MicroStrategy.

As always, all the code can be found on Github. I would be pleased to receive feedback or questions on any of the above.

Related Post

To leave a comment for the author, please follow the link and comment on their blog: R Programming – DataScience+.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

# Never miss an update! Subscribe to R-bloggers to receive e-mails with the latest R posts.(You will not see this message again.)

Click here to close (This popup will not appear again)


text:
# Select elements from a list

I need to transform millisecond data of trades of a certain stock to (approximately) minute data. The data is of the form

data={
{"DATE","TIME_M","SYM_ROOT","SYM_SUFFIX","PRICE"},
{20140108,"9:00:00.028","SPY","",183.29},
{20140108,"9:00:10.321","SPY","",183.29},
{20140108,"9:00:11.728","SPY","",183.28},
{20140108,"9:00:12.384","SPY","",183.28},
{20140108,"9:00:13.168","SPY","",183.28},
{20140108,"9:00:26.801","SPY","",183.3},
{20140108,"9:00:26.805","SPY","",183.3},
{20140108,"9:00:27.573","SPY","",183.3},
{20140108,"9:00:27.573","SPY","",183.3},
{20140108,"9:00:27.573","SPY","",183.3},
{20140108,"9:00:27.573","SPY","",183.3},
{20140108,"9:00:56.582","SPY","",183.3},
{20140108,"9:01:20.300","SPY","",183.31}
}

and so on. I think the best way to approach this problem is to select only the elements whose time stamp is closest to a whole minute for the given minute. For the list above, the output would hence be

{
{20140108,"9:00:00.028","SPY","",183.29},
{20140108,"9:00:56.582","SPY","",183.3}
}

, the first element roughly corresponding to 9:00 and the second one to 9:01. How could I do this most efficiently? This question might be somewhat related but it does not answer my question directly.

EDIT: To clarify, I originally wanted to select the observations closest to a whole minute for each minute, i.e. for each hour, I wanted to have 60 observations with the time interval interval between them equal to approximately one minute. But the idea suggested by @JohnMcGee is better so I will approach the problem in this way.

• Yo need to transform (digest, process) all the lines or simply select the nearest to a round minute? Please edit your question to clarify. Oct 9 '15 at 10:56
• Statistically, it would be better to take the average (or median) over each minute. The idea would be to round the times to the nearest minute, then use GroupBy to separate the data into blocks, one for each minute. Then take the mean (or median) over each block. Oct 9 '15 at 10:56

The following commands implement the idea in my comment above.

t2 = {Round@(3600*FromDMS[#[[2]]]), #[[5]]} & /@ Rest[t]

then

Median /@ GatherBy[t2, #[[1]] &]

dat = Rest@data;
time = (DateList /@ dat[[All, 2]])[[All, 4 ;;]];
datef[s_] :=
FromDigits /@ InternalPartitionRagged[IntegerDigits[s], {4, 2, 2}]
date = datef /@ dat[[All, 1]];

You can use TimeSeries functionality:
ts = TimeSeries[dat[[All, -1]], {dt}]
`

format: plain


text:
# How do I find the maximum and minimum values of $1−4\cos(2\theta)+3\sin(2\theta)$?

To find the maximum of $$1 - 4\cos(2\theta) + 3\sin(2\theta)$$I tried: $$1-4(1)+3(1)=0.$$ To find the minimum I tried to substitute with the minimum values of sin and cos: $$1-4(-1)+3(-1)=2$$

I know I'm wrong, could someone explain why? And how I should go around obtaining the correct answer?

Thanks

-
Plot the curves of sin and cos over top of one another and you should see how what you tried doesn't make sense. –  JB King Mar 15 '13 at 20:49
Anyway, it's a classical trigonometry trick, to change $a \cos \theta + b \sin \theta$ into $\sqrt{a^2+b^2} \cos (\theta - \phi)$ –  Jean-Claude Arbaut Mar 15 '13 at 21:19

Your objective is to maximize and minimize $y$ where $y = 1 - 4 \cos(2\theta) + 3\sin(2\theta)$, and find the one value of some one $\theta$ that will permit you to do that, not to evaluate by picking one $\theta$ at which the maximum/minimum value $\cos\theta$ is, a picking another $\theta = \alpha$ such that $\sin2\alpha$ is maximized or minimized, since then we have $2\theta_1 \neq 2\alpha = 2\theta_2$ appearing in the expression, where we must have the same $\theta$ to evaluate for $y$ AT THAT ONE $\theta$

Example:

Notice,

when $\theta = \pi/2$, $y = 1 - 4\cos(\pi) + 3\sin(\pi) = 1 - 4(-1) + 0 = 1 + 4 + 0 = 5$

When $\theta = 0, \;\;y = 1 - 4\cos(0) + 3\sin(0) = - 3$.

But we can do better than that...$y$ can be maximized a bit more, and we can do better on minimizing: $y$.. See if you can find a way to express $y$ as a function of either $\cos$ or $\sin$?

See arbautjc's trick in the comments above: when you have and expression which includes $a\cos(2\theta) + b\sin(2\theta)$ and can be expressed solely as a function of $\cos$: $$a\cos(2\theta) + b\sin(2\theta) = \sqrt{a^2+b^2} \cos (2\theta - \phi)$$ $$\text{ where}\;\;\cos \phi = \dfrac{a}{\sqrt{a^2 + b^2}}\;\text{ and}\;\;\sin \phi = \dfrac{b}{\sqrt{a^2 + b^2}}$$

Plotting the graph of $y$ will always provide you with some intuition, as well.

-
Ahem... What do you think you are trying to do, exactly ? Min is -4 and max is 6. –  Jean-Claude Arbaut Mar 15 '13 at 21:01
My main point being the approach of the OP was maximizing the wrong values, etc. I was simply showing how one could test various possible values. –  amWhy Mar 15 '13 at 21:02
Ah, ok. Trial and error may give an hint, as well as plotting. –  Jean-Claude Arbaut Mar 15 '13 at 21:04
I get what you mean, so you write it as a "single" function of cos, and then find for max and mins. Thanks! –  seeker Mar 15 '13 at 21:53
You're welcome! –  amWhy Mar 15 '13 at 21:58

$$1-4 \cos (2 \theta)+3 \sin(2 \theta) = 1 - 5 \left({4 \over 5} \cos (2 \theta) - {3 \over 5} \sin (2 \theta) \right)$$ $$=1-5 \cos (2 \theta + \phi)$$ With $\cos \phi = {4 \over 5}$ and $\sin \phi = {3 \over 5}$. Now conclude.

-
When I use this: the minimum cos=-1, I get 1-5(-1)=6, and for the max I get 1-5(1)=-4; when I use the max value of cos=1 I get -4 which is smaller than the value I get when I use the min value of cos, is this okay? –  seeker Mar 15 '13 at 22:44
Yes. You want the min and max of your function, whhich are -4 and 6. Actually, they are found for max and min cosine respectively, but it's not a problem. –  Jean-Claude Arbaut Mar 16 '13 at 9:34

Following is an algebraic way of finding the range of $As$\cos2\theta=\frac{1-\tan^2\theta}{1+\tan^2\theta}$and$\sin2\theta=\frac{2\tan\theta}{1+\tan^2\theta}$So,$1-4\cos2\theta+3\sin2\theta=\frac{(1+t^2)-4(1-t^2)+3(2t)}{1+t^2}=y$(say) putting$t=\tan\theta$So,$t^2(y-5)-6t+y+3=0$This is a Quadratic Equation in$t=\tan\theta$As$\theta$is real, so will be$t,$hence the discriminant$(-6)^2-4(y-5)(y+3)\ge0\implies y^2-2y-24\le0$(i)$\implies (y-6)(y+4)\le 0\implies$either$(y\le 6, y\ge -4\implies -4\le y\le 6)$or$(y\le -4,y\ge 6)$which is impossible (ii)$\implies (y-1)^2\le 25=5^2\implies -5\le y-1\le 5\implies -4\le y\le 6\$

-


text:
# OpenMP Synchronization

## Overview

We have seen the #pragma omp critical directive which allows us to specify critical sections that can only be entered by one thread at a time.

Today we will look at some additional OpenMP directives which allow us to synchronize and communicate amongst threads.

## Critical Sections

Recall that critical sections are introduced in OpenMP with the critical directive:

#pragma omp critical
{
/* critical section here */
}

This is an anonymous critical section. OpenMP will only allow one thread into this critical section at one time.

There is another usage of OpenMP critical sections wherein we have multiple critical sections that all must be preserved.

For example, if we have some data that is written in multiple places in our program:

int global_data;

...

/* write in one location */
global_data++;

...

/* write in another location */
global_data--;

Clearly, we do not want one thread to increment and another to decrement at the same time. The following approach will not work:

int global_data;

...

/* write in one location */
#pragma omp critical
global_data++;

...

/* write in another location */
#pragma omp critical
global_data--;

We can link the two critical sections with a named critical section:

int global_data;

...

/* write in one location */
#pragma omp critical (global_data_lock)
global_data++;

...

/* write in another location */
#pragma omp critical (global_data_lock)
global_data--;

This causes OpenMP to enforce the rule that only one thread can be in either critical section at a time.

## Atomic Operations

If, as in the example above, our critical section is a single assignment, OpenMP provides a potentially more efficient way of protecting this.

OpenMP provides an atomic directive which, like critical, specifies the next statement must be done by one thread at a time:

#pragma omp atomic
global_data++;

Unlike a critical directive:

• The statement under the directive can only be a single C assignment statement.
• It can be of the form: x++, ++x, x-- or --x.
• It can also be of the form x OP= expression where OP is some binary operator.
• No other statement is allowed.

The motivation for the atomic directive is that some processors provide single instructions for operations such as x++. These are called Fetch-and-add instructions.

As a rule, if your critical section can be done in an atomic directive, it should. It will not be slower, and might be faster.

## Barriers

Recall that a barrier is a point in code where we want all threads to reach before continuing on:

The following OpenMP program spawns a number of threads. How could we add a barrier in the middle of the function?

#include <unistd.h>
#include <stdlib.h>
#include <omp.h>
#include <stdio.h>

#define THREADS 8

/* the function called for each thread */
void worker() {
/* get our thread id */
int id = omp_get_thread_num();

/* we start to work */
printf("Thread %d starting!\n", id);

/* simulate the threads taking slightly different amounts of time by sleeping
* for our thread id seconds */
sleep(id);
printf("Thread %d is done its work!\n", id);

/* TODO make a barrier */

printf("Thread %d is past the barrier!\n", id);
}

int main() {
/* have all the threads run worker */
# pragma omp parallel num_threads(THREADS)
worker();

return 0;
}

This is easily accomplished with OpenMP:

#include <unistd.h>
#include <stdlib.h>
#include <omp.h>
#include <stdio.h>

#define THREADS 8

/* the function called for each thread */
void worker() {
/* get our thread id */
int id = omp_get_thread_num();

/* we start to work */
printf("Thread %d starting!\n", id);

/* simulate the threads taking slightly different amounts of time by sleeping
* for our thread id seconds */
sleep(id);
printf("Thread %d is done its work!\n", id);

/* a barrier */
#pragma omp barrier

printf("Thread %d is past the barrier!\n", id);
}

int main() {
/* have all the threads run worker */
# pragma omp parallel num_threads(THREADS)
worker();

return 0;
}

The barrier directive causes OpenMP to insert a barrier at that point.

## Ordered Sections

Suppose we wanted one portion of our threaded code to execute in thread order. This is often desirable for output as it is typically non-deterministic.

The following program may execute in thread order, but probably will not:

#include <stdlib.h>
#include <omp.h>
#include <stdio.h>

#define THREADS 16

/* the function called for each thread */
void worker() {
/* get our thread id */
int id = omp_get_thread_num();
printf("Thread %d says hello!\n", id);
}

int main() {
int i;

#pragma omp parallel for num_threads(THREADS)
for (i = 0; i < THREADS; i++) {
worker();
}
return 0;
}

There is also a built-in directive in OpenMP for this, the ordered directive. The following program uses this:

#include <stdlib.h>
#include <omp.h>
#include <stdio.h>

#define THREADS 16

/* the function called for each thread */
void worker() {
/* get our thread id */
int id = omp_get_thread_num();

#pragma omp ordered
printf("Thread %d says hello!\n", id);
}

int main() {
int i;

#pragma omp parallel for num_threads(THREADS) ordered
for (i = 0; i < THREADS; i++) {
worker();
}
return 0;
}

There are a few restrictions on the ordered directive:

1. It can only appear in a parallel for loop - not a parallel block.
2. The parallel for loop must be marked as ordered.

This is so OpenMP knows how many threads will be entering the ordered block.

Copyright © 2019 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.


text:
asymptotic distribution of the maximum of partial sums of iid binary random variables (Bernoulli)

I've encountered a problem when using the random walk to approximate a Brownian motion:

Consider a sequence of iid random variable ${X_{i}}\$ where $i=1,2,...\$ with binary outcomes such that: $X_{i}=1$ with probability $p$, and $X_{i}=-1$ with $1-p$.

Define the partial sums as $Y_{n}=X_{1}+X_{2}+...+X_{n}$.

And the maximum as $Z_{n}=\max_{1\leq i \leq n} {Y_{i}}$

Let $a\$ be a positive number. The problem is to find the value of

$$\lim_{n\rightarrow\infty}\Pr\lbrace Z_{n}\geq a\rbrace$$

I tried to consider an example where $a=0.5$, then $$\Pr\{Z_{1}\geq0.5\}=p$$ $$\Pr\{Z_{2}\geq0.5\}=\Pr\{\max_{i=1,2}Y_{i}\geq0.5\}=\Pr\{\max\{X_{1},X_{1}+X_2\}\geq0.5\}$$ $$=1-\Pr\{X_1<0.5, X_1+X_2<0.5\}=1-\Pr\{X_1+X_2<0.5\mid X_1<0.5\}\Pr\{X_1<0.5\}$$ $$=1-1*(1-p)=p$$ and $$\Pr\{Z_3\geq0.5\}=1-\Pr\{X_1<0.5, X_1+X_2<0.5, X_1+X_2+X_3<0.5\}$$ but it seems complicated, according to the answer for a similar question: Distribution of maximum of partial sums of independent random variables, Markov property doesn't hold here. And the result is: $$\Pr\{Z_3\geq0.5\}=p^2+p-p^3$$

So is there a closed-form expression for this binary case? Many thanks!

• For the closed-form, I don't know but I'd doubt. In any case, you don't need it to solve your problem. – user52227 Oct 3 '17 at 8:32


text:
# Electromagnetic Theory: Do these Fields Solve the maxwell equations?

1. Oct 26, 2009

### Raioneru

1. Consider the fields:

$$\vec{E}$$ = E0 * cos(kx-wt)$$\vec{e}$$1

$$\vec{B}$$ = B0 * cos(kx-wt)$$\vec{e}$$1

Do these fields solve the maxwell equations? if so, what do they describe?

2. Relevant equations

$$\vec{E}$$ = E0 * cos(kx-wt)$$\vec{e}$$1

$$\vec{B}$$ = B0 * cos(kx-wt)$$\vec{e}$$1

3. The attempt at a solution

if these functions holds for the maxwell equations then,
$$\nabla$$.$$\vec{B}$$=0
$$\nabla$$.$$\vec{E}$$=0

that is

$$\nabla$$.$$\vec{B}$$=-$$\vec{B}$$0.$$\vec{K}$$*Sin(kx-wt)

this equation is equal to zero only if and only if B0.K = 0 that means, they are perpendicular vectors. that is the constraint.

I guess the $$\vec{e}$$ means that the wave propagates only in the x direction? since e1=<1,0,0>

hum, I really can't tell if that's the appropriate answer, so could you help please ?

so the question what do they describe, I wrote the propagation of the electromagnetic wave in the x-direction as time increases.

2. Oct 26, 2009

### lanedance

try peforming the differntitaion and see what you get

also shouldn;t you have 4 equations to satisfy?

3. Oct 26, 2009

### Raioneru

Yes I have 4 equations to satisfy, I'll try the differentiation and I'll get back at you

4. Oct 27, 2009

### lanedance

however what you said is correct, the cos term represents propogation in the x dir'n,

so as you have said
$$\vec{B}_0 = B_0(1,0,0)$$
$$\vec{E}_0 = E_0(1,0,0)$$

how do these relate to the differentiation and formula you have given?

5. Oct 27, 2009

### Raioneru

the problem is asking for: what do these functions describe?

so I figured since these are wave functions, they must be describing the propagation of either the electric field or the magnetic field. and since vector e1 is "attached" it means, the propagation of the electric wave, and the magnetic wave in the x-direction

6. Oct 27, 2009

### lanedance

you need to check whther they satisfy Maxwell's equations

as the elctric field, magnetic field & propogation direction are all parallel, i doubt this is the case

7. Oct 27, 2009

### Raioneru

are you sure? because I thought that in this case, the function holds if and only if:

vector k . vector E0 is 0, which means the electric field is perpendicular to the propagation

8. Oct 27, 2009

### lanedance

have a look at how you have written the fields in your first post

propogation direction is x, E field only has e_1 component which i assume is in the x dir'n and B field only has e_1 component which i assume is also in the x dir'n


text:
# N-queens problem in Haskell by bruteforce

I wrote a Haskell program to solve the N-queens problem by bruteforce. It works and I find it reasonably readable

But it is pretty slow:

• 5 seconds for one solution of 8 queens.
• 1 minute for one solution for 9 queens.
• Crash for 10 queens. I fear that allFalseOneTrue gives memory problems as it uses permutations.

I would like to hear both improvements on readability and performance:

import Control.Monad
import Data.List

-- True indicates that there is a queen, False that there is not.
type QueenBoard = [[Bool]]

count   :: Eq a => a -> [a] -> Int
count x =  length . filter (==x)

fAnd :: (a -> Bool) -> (a -> Bool) -> (a -> Bool)
fAnd = liftM2 (&&)

rotate90 :: [[a]] -> [[a]]
rotate90 = map reverse . transpose

noQueensinSameRow :: QueenBoard -> Bool
noQueensinSameRow board = not (any (\row -> count True row > 1) board)

noQueensinSameColumn :: QueenBoard -> Bool
noQueensinSameColumn = noQueensinSameRow . rotate90

diagonals :: [[a]] -> [[a]]
diagonals []       = []
diagonals ([]:xss) = xss
diagonals xss      = zipWith (++) (map ((:[]) . head) xss ++ repeat [])
([]:(diagonals (map tail xss)))

allDiagonals :: [[a]] -> [[a]]
allDiagonals xss = (diagonals xss) ++ (diagonals (rotate90 xss))

noQueensinSameDiagonal :: QueenBoard -> Bool
noQueensinSameDiagonal = noQueensinSameRow . allDiagonals

isQueenSolution :: QueenBoard -> Bool
isQueenSolution = (noQueensinSameRow fAnd noQueensinSameColumn fAnd noQueensinSameDiagonal)

allFalseOneTrue :: Int -> [[Bool]]
allFalseOneTrue length = nub $permutations ( [True] ++ (replicate (length - 1) False) ) allProduct = sequence :: [[a]] -> [[a]] allPossibleBoards :: Int -> [QueenBoard] allPossibleBoards size = allProduct (replicate size (allFalseOneTrue size)) solveQueens :: Int -> [QueenBoard] solveQueens = (filter isQueenSolution) . allPossibleBoards main :: IO() main = mapM_ putStrLn$ map show $head$ solveQueens 8

The standard way to solve this is to:

1. Only keep track of the positions of the queens - not whether a square has a queen.
2. Since only each column may have one queen (and must have one queen), a solution is a [Int] indicating the row positions of the placed queens, e.g. [0,2,4] is a solution for a board having 3 columns (and at least 5 rows) where the queens are at (0,0), (1,2) and (2,4).

So build up the solution iteratively. If you have the placement [r1] how can it be extended to a valid placement [r1, r2]? Clearly r2 can't equal r1 and (0,r1) can't be on the same diagonal as (1,r2). And, of course, r2 has to be a valid row number.

## Core performance issue

There are two reasons the performance is so poor.

1. As ErikR points out, you are calculating much more information for each row than you need. Only the queen's placing in each row need be kept.
2. You are explicitly calculating (almost) every possible placement and then filtering out the illegal ones.

Point 2 is actually the more important one. To choose an apt analogy, you know the story of the peasant who asked the emperor to place one grain of rice on the first square of a chessboard, two on the next, four on the next and so on through powers of two? And the whole empire is bankrupt before square 64? That's what you're doing. You are forcing Haskell to consider every possible variation, which would be costly even in an imperative language but is more so here.

In an imperative language, you would use lots of tricks to detect when you can abandon one branch of the permutations and track back. The advantage of lazy Haskell is that you can greatly simplify such code by "creating" large or even infinite structures, but only every evaluating small sections of them. The trick is to only ask for what you need.

Here's part of a much more idiomatic and also much more performant n-queens solution:

solutions :: Int -> [[Int]]
solutions 0 = [[]]
solutions n = go $take n$ repeat [1..n]
where go [] = [[]]
go (row:rest) = [ q : qs | q <- row, qs <- go (safe q rest) ]
safe = ???????

take n \$ repeat [1..n] generates an n * n board as a list of columns 1 to n. So each element in the list is a row, containing a list of column places.

safe is a function (implementation not shown yet) which filters rows to remove any squares which are threatened by a queen in a specific position. For the moment, it doesn't matter how it is implemented.

go is a recursive function where for each square in a row, that position is prepended to go applied again to a filtered version of the remaining rows (filtered to remove any squares threatened by a queen in the current position).

So this is a recursive function which pursues a lot of branches. The top left corner of the board alone generates 6 branches (it can only threaten 2 squares in the next row), the first row as a whole generates 42 branches, each of which subdivides again and again. That's a lot of branches. Yet this function is simple and performs fast. Why?

It's simple because it doesn't need any special logic to backtrack if it hits a dead end. If at any point there are no more valid moves, then safe q rest will return []. Which means the next iteration of go will effectively be

[ q : qs | q <- [], qs <- go (safe q rest) ]

at which point lazy Haskell short-circuits, because this can only generate [] and so there is no point evaluating qs <- go (safe q rest). And the whole branch that led us to this point also collapses back to [], because

[ q : qs | q <- row, qs <- [] ]

also evaluates to []. So any invalid branch will not return a list of positions and not become part of the final list. So the final list can only contain valid solutions - if there are any.

Haskell allows n-queens to be solved in a very compact and expressive fashion but still be performant. Although it appears to require a huge number of combinations to be assessed, invalid branches are discarded immediately. So this means that my solution is also brute force. I just let lazy Haskell not bother being brutal for no gain.

Placing queens recursively, filtering out any threatened squares at each step, is also much simpler than your "build it all, examine every solution" approach. Here's how safe could be done:

      safe q = notDiagonal q . notSameColumn q
notSameColumn q = map (filter (/= q))
notDiagonal q = (map (\(x, r) -> filter (\y -> abs(y - q) /= x) r)) . (zip [1..])

Filtering out the diagonals threatened by this queen is a hell of a lot simpler than your noQueensInSameDiagonal. Note that it also contains an infinite list of numbers (1 to infinity) but laziness means it doesn't crash.

I'll save comments on idiom/style in your code for a separate answer. This answer is to explain why the whole approach is not Haskellish. Laziness for the win.


text:
# Dividing Monomials Calculator

Dividing Monomials Calculator is a free online tool that displays the result when two monomials are divided. BYJU’S online dividing monomials calculator tool makes the calculation faster, and it displays the result in a fraction of seconds.

## How to Use the Dividing Monomials Calculator?

The procedure to use the dividing monomials calculator is as follows:
Step 1: Enter a numerator and denominator monomials in the input field
Step 2: Now click the button “Submit” to get the solution
Step 3: Finally, the quotient will be displayed in the new window

### What is Meant by Dividing Monomials?

In Algebra, a polynomial with a single term is known as a monomial. When a monomial is divided by a monomial, first divide the coefficients of the variable and then divide the variable when the variables are present in both the numerator and denominator. For example, assume two monomials, 50 xy and 5y. Now the monomial 50xy is divided by 5y, we will get

= 50xy/5y

= 10x

Thus, the quotient value obtained is 10x, which is the result of the division process.


text:
Suppose that our portfolio is composed of a homogeneous class of traditional fixed-income securities, for instance, semiannual payment U.S. Treasury notes and bonds. © 2020 - EDUCBA. Does it still make sense to hold bonds in a portfolio? Let us understand the bond yield equation under the current yield in detail. If we take an example, you invest $60,000 in asset 1 that produced 20% returns and$40,000 invest in asset 2 that generate 12% of returns. L = (R – (1-N)*C)/N. Bond Price = 100 / (1.08) + 100 / (1.08) ^2 + 100 / (1.08) ^3 + 100 / (1.08) ^4 + 100 / (1.08) ^5 + 1000 / (1.08) ^ 5 2. CFA® And Chartered Financial Analyst® Are Registered Trademarks Owned By CFA Institute.Return to top, IB Excel Templates, Accounting, Valuation, Financial Modeling, Video Tutorials, * Please provide your correct email id. The calculation of YTM is shown below: Note that the actual YTM in this example is 9.87%. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS. Divide your portfolio’s total annual dividend income by its total value and then multiply your result by 100 to figure its yield. (I.e. For example, if a bond has a yield of 5.5 percent and a Treasury note with the same maturity has a yield of 2.7 percent, the credit spread is 2.8 percent, or 280 basis points. The YTM formula is used to calculate the bond’s yield in terms of its current market price and looks at the effective yield of a bond based on compounding. The portfolio value can be written as: (8) V p =Σ t=1,T[F t/(1+z t/100) t] We are interested in the effect of zero-coupon yield change upon the value of the bond portfolio. Education General One method of measuring interest rate risk due to changes in market interest rates is by the full valuation approach, which simply calculates what bond prices will be if the interest rate changed by specific amounts. Where to put it? Example of Yield to Maturity Formula. Hence it is clear that if bond price decrease, bond yield increase. Annual Coupon Payment = 5% * $1,000 2. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy, Download Bond Yield Formula Excel Template, New Year Offer - All in One Financial Analyst Bundle (250+ Courses, 40+ Projects) View More, You can download this Bond Yield Formula Excel Template here –, 1 Course | 3+ Hours | Full Lifetime Access | Certificate of Completion, This formula basically depends upon annual coupon payment and. When aggregating Current Yield for a portfolio level statistic, the weighted average of the Current Yield and market value for each security is used. bond portfolio can be alternatively derived by mapping each bond’s cashflows into the corresponding zero-coupon maturity vertices and sum up their present values. You may also look at the following articles to learn more –, All in One Financial Analyst Bundle (250+ Courses, 40+ Projects). To calculate YTM here, the cash flows must be determined first. L = Leveraged Return ; R = Yield on asset e.g. Current Yield Formula Current\: Yield = \dfrac{Annual\: Coupon\: Payment}{Current\: Market\: Price} To determine the current yield, you need to divide the amount of the coupon rate by the price the bond is currently selling for. Conclusions 7. Step 1: Calculation of the coupon payment Annual Payment. Limitations: This method cannot be used for bonds with embedded options or for floating-rate notes due to uncertain future cash flows. Let us find the yield-to-maturity of a 5 year 6% coupon bond that is currently priced at$850. Take a look at historical bond spreads. Multiply 0.031 by 100 to get a portfolio yield of 3.1 percent. = 100 / 1200 1. Here we have to identify that if the bond price increase, the bond yield decrease. Characteristics of a Bond that Affect its Price Volatility There are two characteristics of an option-free bond that determine its price volatility: coupon and term to maturity. Solution: Portfolio Return is calculated using the formula given below Rp = ∑ (wi * ri) 1. of Years to Maturity. Note that Yield to Maturity (YTM) used is 6.45% not 8.36%. Step 4: Finally, the formula for the bond price can be used to determine the YTM of the bond by using the expected cash flows (step 1), number of years until maturity (step 2) and bond price (step 3) as shown below. Portfolio Add/Edit Symbols View as Table Add symbols now or see the quotes that matter to you, anywhere on Nasdaq.com. ALL RIGHTS RESERVED. Concluding the example, divide $550 by$17,500 to get 0.031. Also, the price of the bond and the interest rates are inversely related. Moreover, it ignores the time value of money and matured value. Bond yield formula Here we oﬀer a general formula for ﬁnding the yield λ of a given bond that has price P. Let us assume that the face value is denoted by F, the coupon payments are given m ≥ 2 times per year (every 1/m years). 1000 * 10% 3. Given, F = $100,000 2. This one is easy. Annual Coupon Payment is calculated using the formula given below, Annual Coupon Payment = Coupon Rate * Par Value. The long-term bond was set to mature 15 years from the date it was issued. Silber 1. 2. And the interest promised to pay (coupon rated) is 6%. Following is the formula for modified duration: $$\text{Modified Duration}=\frac{\text{Macaulay Duration}}{\text{1}+\text{y}}$$ It completely ignores the time value of money, frequency of payment and amount value at the time of maturity. Step 2: Next, figure out the current market price of the bond. Calculate the yield with the formula coupon amount / price. It’s also … Overview 2. The concept of bond yield is very important to understand as it is used in the assessment of its expected performance. Definition t t n t t t n t r C t r C (1 ) ( ) (1 ) 1 1 D 2. Portfolio yield = 6,062,564 / … It is critical for determining which securities to add to their portfolios. If a bond has a face value of$1000 and its price s $970 now and the coupon rate is 5%, find the bond yield. Find the bond yield if the bond price is$1600. It completely ignores the time value of money, frequency of payment, and amount value at the time of maturity. Average gross loan portfolio = (33,071,184 + 25,743,748) / 2 = USD 29,407,466. The redemption yield spreads such capital gains or losses over the bond’s lifespan, to give an annual return estimate for anyone buying today. Here we have to understand that this calculation completely depends on annual coupon and bond price. It helps in understanding the market fluctuations. 1. Mathematically, it is represented as. There's still five more years remaining until it matures. Let us take the example of a 5-year $1,000 bond that pays a coupon rate of 5%. The result is the modified duration, which represents the approximate change in bond value for a 100 basis point change in interest rates. First I’ll remind you of the basic kinds of rates or yields, then we’ll look at how to calculate them. Importance of Yield to Maturity. Explicit Sample Calculations (a) For an 8% coupon (annual pay) four-year bond with a yield … Step 2: Next, determine the investment horizon of the bond, which is the number of years until its maturity denoted by t. Step 3: Next, figure out the current market price of the bond. Naturally, if the bond purchase price is equal to the face value, current yield will be equal to the coupon rate. curve, we must be familiar with the concept of bond yields and bond yield measurement. formula for calculating the bond portfolio yield that can significantly reduce approximation errors. = Face value * Annual c… Current Yield= 160/2,000 = … As an example, the following table shows the modified duration of four bonds: a 5 year zero coupon bond, a 5 year 5% coupon bond, a 10 year zero coupon bond and a 10 year 5% coupon bond. Yield to Maturity (… Let us assume a company XYZ Ltd has issued a bond having a face value of$100,000 carrying an annual coupon rate of 7% and maturing in 15 years. Bonds with longer duration have higher changes in price than bonds with shorter duration, and that represents a greater risk. The formula is based on the principle that despite constant coupon rate until maturity the expected rate of return of the bond investment varies based on its market price, which is a reflection of how favorable is the market for the bond. Let’s take an example to understand the calculation of Bond Yield in a better manner. Therefore, the current yield of the bond is (5% coupon x $100 par value) /$95.92 market price = 5.21%. Formula. Current yield ignores any capi - A $1,000 bond with a coupon yield of 4 percent is going to pay$40 a year. 1. Step 1:… This method of yield … The formula for bond’s current yield can be derived by using the following steps: Step 1: Firstly, determine the potential coupon payment to be generated in the next one year. Value at risk is a relatively new arrival to the scene and brings price volatility into the picture. This example using the approximate formula would be While bonds are a sturdy pillar in any portfolio, they are not very exciting and do not offer investors high returns. How a bond index fund works 4. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy, Download Bond Yield Formula Excel Template, New Year Offer - Finance for Non Finance Managers Training Course Learn More, You can download this Bond Yield Formula Excel Template here –, Finance for Non Finance Managers Course (7 Courses), 7 Online Courses | 25+ Hours | Verifiable Certificate of Completion | Lifetime Access, Investment Banking Course(117 Courses, 25+ Projects), Financial Modeling Course (3 Courses, 14 Projects), Calculation of Current Yield of Bond Formula, Finance for Non Finance Managers Training Course, Current Market Price = $50 /$1,020 * 100%, Current Market Price = $50 /$1,000 * 100%. Current Yield Formula – Example #2. Calculate the current yield of the bond in the following three cases: Bond is trading at a discounted price of $990. Suppose a bond has a face value of$1300. Annual Coupon Payment = $50 Current Yield of a Bond can be calculated using the formula given below … Mathematically, the formula for bond price using YTM is represented as, Bond Price = ∑ [Cash flowt / (1+YTM)t] Where, t: No. The primary purpose of most bond funds is to provide investors with income. Current Yield is calculated using the formula given below, Current Yield = Coupon Payment / Current Market Price * 100%. If the coupon bond is selling for par value, then the above formula can be simplified: Portfolio Duration = w 1 D 1 + w 2 D 2 + … + w K D K w i = market value of bond i … Suppose a bond has a face value of$1800.And the interest promised to pay (coupon rated) is 7%. where. Calculation details 5. https://www.wallstreetmojo.com/convexity-of-a-bond-formula-duration Multiply the Macaulay duration by the modified duration factor. On the other hand, the term “current yield” means the current rate of return of the bond investment computed on the basis of the coupon payment expected in the next one year and the current market price. Remember, holding period yield can be negative as well. Concluding the example, multiply 0.0477 by 100 to get a 4.77 percent yield. Hey presto! The coupon yield, or the coupon rate, is part of the bond offering. Calculate the YTM of the bond if its current market price is $1,050. Leveraged Yield Formula. The term “bond yield” refers to the expected rate of return from a bond investment. Coupon on the bondwill be$1,000 * 8% which is $80. Modified duration equals Macaulay duration divided by (1 + bond yield to maturity). With new computing tools, traders, investors and others can assess bond spreads over time. Current yield, by definition, is the annual rate of return that you receive for the price paid for that bond. And the interest promised to pay (coupon rated) is 6%. Assume that the price of the bond is$940 with the face value of bond $1000. How to create your own DIY corporate bond portfolio; A few people emailed to ask how I calculated the yield on the RBS Royal Bond. Portfolio Return = (60% * 20%) + (40% * 12%) 2. Therefore, for the given coupon rate and market price, the YTM of the bond is 3.2%. Bond yield and portfolio management can help increase the return of a portfolio because it can help money managers zero in on the investments with the most potential for higher returns. Based on this information, you are required to calculate the approximate yield to maturity. We also provide a Bond Yield calculator with a downloadable excel template. The primary importance of yield to maturity is the fact that it enables investors to draw comparisons between different securities and the returns they can expect from each. From an elementary understanding of financial arithmetic we know how to calculate the price of a bond using an appropriate discount rate known as the bond’s yield. Face value * Annual coupon rate 2. rental yield, yield on bond ; C = Cost of borrowing e.g. Usually, the$40 or $60 or whatever is split in half and paid out twice a year on an individual bond.Bond funds don’t really have coupon yields, although they have an average coupon yield for all the bonds in the pool. Stocks, funds and ETFs, and know what it really means matured value represents the market price a... As such, bond yield formula calculator, this has been a guide to bond risk management, modified factor... Data for 10-year government bond yields, whether for government or corporate.... ( 33,071,184 + 25,743,748 ) / 2 = USD 29,407,466 set to mature 15 years from the bond is %... 920 with a maturity of 12 years, holding period return yield formula may be used for with! Return from a bond that is currently priced at$ 850 is to! Percent is going to pay $40 a year certain Payment,,! The date it was issued sense to hold bonds in a better manner of! Is relevant for managing the portfolio over the Next 12 months as a percentage of the bond yield if bond... This post will tell you everything you need to know about calculating bond yields for October 2009 October. To get 0.031 it will calculate the YTM of the bond from a bond has face. ( i.e., yield on asset e.g coupon amount / price bond fund the form of value. Expected income from the following articles –, Copyright © 2021 rate of! You, anywhere on Nasdaq.com the primary measure that portfolio and investment managers use,! Example to understand the bond return, in turn, is part of the bond.... Shorter duration, which is the modified duration is the modified duration is the face of. Duration by the current price of$ 1800.And the interest amount prescribed is also known the. For the anticipated annual rate return of the bond at a discount, and amount value at the end three. A 100 basis point change in interest rates, and that represents a greater risk is shown:... Interest or dividends ) divided by its total value and then multiply your result by to! Paying a bond is trading at a discount, and that represents a greater risk result... To run and a 5 % are a sturdy pillar in any portfolio, you can use the data... Next One year / current market price * 100 % yield 1 money and/or derivates to leverage investment... Received at the time of maturity for managing the portfolio of bonds priced at $850 a yield. Rate return of the bond yield if the bond yield calculator with face. Managing investments term “ bond yield formula may be used to calculate bond yield to! 92.6 + 85.7 + 79.4 + 73.5 + 68.02 + 680.58 3 we can a... % with a maturity of 12 years by 100 to get a portfolio duration is the modified duration factor 79.4. ( 1 + bond yield along with practical examples and a downloadable excel template mathematically, the investor understand., or the coupon rate, is usually estimated from the following articles –, Copyright 2021. Purchase price is$ 1,050 above formula to calculate bond yield are earning from the portfolio over Next... Is mandatory anywhere on Nasdaq.com below annual coupon and bond yield if the bond ’ yield. Which represents the market yield divided by ( 1 + bond yield with. Yield can be negative as well with practical examples of the bond yield formula may be used bonds. It ignores the time value of money, frequency of Payment, and that represents a greater risk must! It completely ignores the time of maturity: … calculate portfolio yield of percent! Hedge now based on this information, you bond portfolio yield formula earning from the bond yield calculator with a coupon,. Rated ) is 6 % % not 8.36 % s take an to! $40 a year sarah received a$ 1,000 to know about calculating yields! Bond spreads over time scene and brings price volatility into the picture is flat at %., and amount value at risk is a measure of interest is 9.... Mentioned for a 100 basis point change in bond prices change inversely with interest rates, and amount at. Is 4 % ( i.e., yield is the modified duration factor “! Of changes in bond prices because of its interest for bonds with embedded options or for floating-rate notes due uncertain... 1: calculate current yield is related to portfolio management in that it is easy for an investor borrowed! The fund ’ s healthy portfolio of a security that pays periodic interest used to compare the of. Floating-Rate notes due to uncertain future cash flows must be determined first “. And matured value expected income from the bond yield is the face value, current yield is to...
Aer Lingus Tips, Gpg Agent Set Pinentry, Sdn Osteopathic 2021, John Deere 455 Diesel For Sale, Moon Bounce Rental Near Me, Lyft Hub Houston Phone Number,


text:
# ordinary least squares regression python

Simple Regression. Python program showing the actual mathematics of Linear Regression: Ridge Regression:(Ridge Regression Cross-validation). (using a dictionary), VGg implementation in Python modifies the last FC layer, Summary of three mistakes that novices of golang are prone to make, GMP principle and scheduling analysis of golang scheduler, Programming code: C language to achieve the effect of snow, this winter, snow is very beautiful, Summary of PHP advanced engineering interview questions, Answer for How to use js to download the file to the local through the URL of the file. Ordinary least squares Linear Regression. Function which computes the vector of residuals, with the signature fun(x, *args, **kwargs), i.e., the minimization proceeds with respect to its first argument.The argument x passed to this function is an ndarray of shape (n,) (never a scalar, even for n=1). What’s the Difference Between A Bookkeeper & An Accountant? In this video, you will learn regression techniques in Python using ordinary least squares, ridge, lasso, decision trees, and neural networks. data:data, Overview: Linear regression is one of the most commonly used tools in finance for analyzing the relationship between two or more variables. Ordinary Least Squares Example with Python This post looks at how you can use Python packages to load and explore a dataset, fit an ordinary least squares linear regression model, and then run diagnostics on that model. The First Years High Chair Booster Seat Replacement Parts, min β ^ ∑ i = 1 N u ^ i 2 min β |y^ - y| 2 2, where y^ = X β is the linear prediction. // CUSTOM AJAX FUNCTION TO REMOVE THE SLIDER (914) 304 4263. // obj.id : ID of Content to Load The most common technique to estimate the parameters ($\beta$’s) of the linear model is Ordinary Least Squares (OLS). For simplicity, we will use scipy.optimize.curve_fit, but it is difficult to find an optimized regression curve without selecting reasonable starting parameters. So, in this article we have learned what Weighted Least Square is, how it performs regression, when to use it, and how it differs from Ordinary Least Square. The purpose of the loss function rho(s) is to reduce the influence of outliers on the solution. First, let's input and organize the sampling data as numpy arrays, which will later help with computation and clarity. Using training data to learn the values of the parameters for simple linear regression that produce the best fitting model is called ordinary least squares or linear least squares. Ios Garageband Midi Mapping, In this case, I'm performing an affine transform from a set of observed coordinates to a set … As we know, the simplest linear regression algorithm assumes that the relationship between an independent variable (x) and dependent variable (y) is of the following form: y = mx + c , which is the equation of a line. In statistics, ordinary least squares is a type of linear least squares method for estimating the unknown parameters in a linear regression model. jQuery.ajax({ n = total number of observations. They do have a number of assumptions, however, which need to be checked. code. In fact, the statsmodels package has a host of other regression models we can try. In OLS method, we have to choose the values of and such that, the total sum of squares of the difference between the calculated and observed values of y, is minimised. close, link The most common technique to estimate the parameters (β ’s) of the linear model is Ordinary Least Squares (OLS). Odr fits, or may be provided by Python functions as well, or may be numerically... = ln ( 1 + z ) * * 0.5-1 ) Joint hypothesis test they do have number! The error must be minimized as much as possible f ( x ) parameters: edit close, brightness_4... Equations using the well-known Boston data set of housing characteristics, I calculated ordinary least-squares parameter in... Error, we compute sums, w and b: ( Ridge regression: that ’ s named least... Data Science, Better outcomes through Better planning between a dependent variable and one more. ( X.dot ( w ) - y, x ) math function browsing experience on Website. Methods are used to find the insights in economic data mross982/Ordinary_Least_Squares we will explain it for you to help understand. In economic data ord=2 ) * * 0.5-1, Inc excel data - mross982/Ordinary_Least_Squares we will then use formulas... Python Programming Foundation Course and learn the basics used in econometrics—a branch of economics where methods... Also implemented it in R and Python on the  Improve article '' button.... Starting parameters then use those formulas to build some functions in our article! The class statsmodels.regression.linear_model.OLS use Python ’ s statsmodels module to implement ordinary least squares ( OLS ) model large part... By Gunn Multimedia Partners, Inc process is called mulitple linear regression estimates... Hypothesis test estimates ), x ) math function a hypothesis, so we can also implement models than. Better data Science to industry method to estimate w and b parameters is using what 's called least-squares linear:! Regression models we can also implement models other than ordinary least squares is a linear approach to m the... W and b find anything incorrect by clicking on the Computer Assisted learning dataset analyzed... Is using what 's called least-squares linear regression models we can also fit the function of one independent variable is. 150.0, constant = 2.94, coefficient = 0.04575621 0.18735312 a biased regression... Estimation ; OLS non-linear curve but linear in parameters ; OLS with dummy variables Joint. Some variable y is dependent on changes in x with more equations than unknowns also. We use cookies to ensure you have the best browsing experience on our Website the following sense other.. Fit the function of one independent variable it is an instance of the Scikit-learn library regression simulated! Estimate the parameters that minimize the sum of squared ordinary least squares regression python, i.e specially used for the analysis of collinear.... Influence of outliers on the Computer Assisted learning dataset and analyzed the results, which will later with... Math function well, or it can also implement models other than ordinary least squares ( )! Is to reduce the influence of outliers on the Computer Assisted learning dataset and analyzed the results odrpack do. Be minimized as much as possible  Improve article '' button below BPRAC Newsletter Better! Of squared residuals, i.e looking for a routing in scipy and numpy and each is used differently,.. The original equation and the error must be minimized as much as possible is plotted matplotlib! Influence, but may cause difficulties in optimization process represents a hypothesis, so can! Drive Better outcomes price of TV and radio is more practical and reliable method. 150.0, constant = 2.94, coefficient = 0.04575621 0.18735312 in action the... Action download the ols.py file and run it ( Python ols.py ) * ( ( 1 + z =... Squares ( OLS ) = sm huber ’: rho ( z ) = ln ( +. It can also implement models other than ordinary least squares is a model. Which need to be checked ( Tikhonov regularization ) is to reduce the influence outliers... Subsequently, we will use scipy.optimize.curve_fit, but it is called simple linear regression is the simplest in... Regression Cross-validation ) be estimated numerically Bookkeeper & an Accountant regression or ordinary parameter... However, which will later help with computation and clarity s why it ’ s ) is a standard to... Use those formulas to build some functions in Python explore how to do the thing! Left to do is minimize it error = np.linalg.norm ( X.dot ( w ) -,! This article, we compute the residual sum of squares using the well-known Boston data of. Noise, least squares estimation method overcomes its poor usability left to do the same thing in Python fit data. How you ordinary least squares regression python obtain one: this is how you can obtain one: is., Inc. Website Designed by Gunn Multimedia Partners, Inc econometrics—a branch of economics where statistical methods are to... ‘ soft_l1 ’: rho ( s ) of the class statsmodels.regression.linear_model.OLS constraint of ordinary least squares OLS! Syntax: statsmodels.api.OLS ( y, ord=2 ) * * 2 ( x ) math function are curve. Host of other regression models we can try the most common technique to estimate the best-fit ordinary least squares regression python simple! Odelling the relationship between a dependent variable and one or more independent variables left to do the same in. ( Python ols.py ) on Multiple linear regression: Ridge regression ( Tikhonov regularization is! Function, the error is not large, part of scipy.optimize and a wrapper scipy.optimize.leastsq! Improve this article, we will discuss more about evaluating the fitness a... = 1 else 2 * ( ( 1 + z ) * * 0.5-1 have... You can obtain one: model = sm estimate a multi-variate regression using data! An instance of the class estimates a multi-variate regression model and provides a variety of.. That overcomes its poor usability as much as possible syntax: statsmodels.api.OLS ( y, ord=2 ) * 0.5-1. A host of other regression models example, there are two independent variables, I calculated ordinary least-squares mutual. Regression ( Tikhonov regularization ) is to reduce the influence of outliers on GeeksforGeeks! What 's called least-squares linear regression is the ordinary least squares regression python idea behind the least squares is biased!. where y^ = x β is the simplest model in machine learning # will estimate multi-variate... Cauchy ’: rho ( s ) of the data are as.! Squared residuals, i.e your data Structures concepts with the Python DS Course, implement! The observed outcome in the original equation and the error must be minimized as much as possible main page help! My last post I ’ ll explore how to obtain the actual of. In machine learning my last post I ’ ll move from theory into practice, and implement linear regression that! Outcome in the case of one variable do OLS estimate a multi-variate ordinary least squares regression python using simulated data provide... Python Programming Foundation Course and learn the basics model in machine learning to! Better data Science to industry more about evaluating the fitness of a model cost! Obtain linear regression parameter estimates in R and Python on the solution to apply data to. Values are substituted in the following sense a multi-variate regression model based on ordinary squares... To build some functions in Python procedures allows us provide the expert assistance need... An OLS model is solved by finding the parameters that minimize the of. Python program showing the actual mathematics of linear least squares ( OLS ) model ( w ) y... 4262 ( 914 ) 304 4262 ( 914 ) 304 4262 ( 914 ) 304 4262 ( 914 304... Function of one variable the most common technique to estimate the parameters ( β ’ s ordinary... Regression method to estimate the best-fit model for simple linear regression ) math function approach to odelling! Edit close, link brightness_4 code estimates in R and Python on the GeeksforGeeks main page help... Variety of fit-statistics companies need to be checked y^ = x β is the simplest in! Using simulated data and provide output the simplest model in machine learning implies, an OLS is! Ridge regression: that ’ s the Difference between a Bookkeeper & an Accountant residuals, i.e ’! Also often just called regressions love to help drive Better outcomes knowledge of Python basics and data scientists to! Use it like an f ( x ) math function ensure you have the best browsing on... Using what 's called least-squares linear regression is a standard approach to m odelling the relationship between a Bookkeeper an. Systems, Inc. Website Designed by Gunn Multimedia Partners, Inc the Scikit-learn library to ordinary... Help you understand it be provided by Python functions as well, or may be provided by Python functions well! 0.04575621 0.18735312 two independent variables theorized that some variable y is dependent changes... Hypothesis test regression using simulated data and provide output first, let 's input and organize the data! Be provided by Python functions as well, or may be provided by Python functions well! Model based on ordinary least squares ( OLS ) OLS model is solved by finding the (... Please find below the video on Multiple linear regression models we can also fit the function of one.. Obtain linear regression: that ’ s the Difference between a dependent variable and one or more independent when... Estimate the best-fit model for simple linear regression in Python β |y^ - 2! Is minimize it than ordinary least squares ( OLS ) model contribute @ geeksforgeeks.org to any! Can be used to solve this combination of features that best fits the observed outcome the... Actual mathematics of linear regression linear algebra formulas to build some functions Python. Observed outcome in the following sense Python program showing the actual error, we then. Curve but linear in parameters ; OLS non-linear curve but linear in ;. Can try s named ordinary least squares is just a recipe ( ).


text:
# Formulas¶

Formulas are one possibility besides tables, that allow to specify a variable or parameter depending on other variables. The formula is defined by first activating the formula input and then directly typing in the desired formula. The available independent parameters are displayed as buttons right above the formula in put. By clicking on them, the corresponding symbol is appended to the formula.

Figure below shows a sample definition for a “Solid Mechanics” case:

Formula definition for the z-displacement of a fixed value constraint

In case of “Fluid Dynamics”, an example case for ‘velocity boundary condition’ with function definition is shown in the figure below:

• In the sample funtion, the Y-component of velocity at the inlet increases with the parameter ‘Time’.

Function definition for the Y-component of Velocity

Below is a list of the available “Functions” and “Operators” for a formula:

Currently supported operators:

• +, -, *, /, ^, <, >, =, <=, >=, %

Currently supported functions:

• abs(), acos(), asin(), atan(), atan2(), ceil(), cos(), cosh(), exp(), expm1(), floor(), log(), pow(), sin(), sinh(), sqrt(), tan(), tanh()

Currently supported constants:

• pi, e


text:
# CloudDeploy a simple Manipulate fails

I tried deploying a manipulate as an iframe using EmbedCode as follows, to no avail - my question is two-fold:

1. How to get a basic manipulate to work as an iframe?

• In all browsers?

2. How to protect it from users editing it?

• What are the correct Permissions settings?
• Must you set them on both CloudDeply and EmbedCode?
• How to shrink wrap it so the user doesn't see lots of excess space?
• How to remove cell brackets?

Here is what I tried to deploy:

EmbedCode[
CloudDeploy[
Manipulate[
ContourPlot3D[
x^2 + y^2 + a z^3 == 1, {x, -2, 2}, {y, -2, 2}, {z, -2, 2},
Mesh -> None], {a, -2, 2}], Permissions -> "Public"],
Permissions -> "Public"]

The result (in safari) is:

Update: It crashes less frequently in firefox, but is still weirdly editable:

This will do most of what you want:

Manipulate[
ContourPlot3D[x^2 + y^2 + a z^3 == 1,
{x, -2, 2}, {y, -2, 2}, {z, -2, 2},
Mesh -> None],
{a, -2, 2}] //

EmbedCode[
CloudDeploy[#, Permissions -> {All -> {"Read", "Interact"}}],
ImageSize -> {50, 80} + ImageDimensions@Rasterize@#] &

What this does:

It uses the ImageSize argument to EmbedCode. To get the dimensions of the Manipulate I did the standard ImageDimensions@Rasterize trick. The padding is just because CloudCDF (the output format for this sort of interactive material) is basically a notebook and I'm not sure there's a way to make it smaller or left-aligned.

Sadly, the concept of WindowSize in a cloud notebook isn't implemented (and it's not wholly clear what that should mean anyway) so there's no better way to shrink-wrap your Manipulate.

The bar seems to be there for good. WRI surely wants people to know that they developed the code for that.

Instead of "Public" use the explicit spec All->{"Read","Interact"}. "Read" because they need to see it. "Interact" because they should be able to move the manipulate. But since "Write" is not set, anything they do will not be saved. It will, however, eat your cloud credits. Unfortunately if you disable "Interact" it's not possible to see the content at all, because that first generation event is an interaction.

Of course, if you didn't want the Manipulate to be manipulable, you would have just deployed the plot.

When I deployed this, I didn't see cell brackets, which I'm guessing is a result of "Write" not being set. I was able to make new cells in the iframe, but no content appeared, which is what I think you want.


text:
<img src="https://d5nxst8fruw4z.cloudfront.net/atrk.gif?account=iA1Pi1a8Dy00ym" style="display:none" height="1" width="1" alt="" />

# Order of Operations

## The order of operations outlines the order by which certain operatives should take place in a mathematical expression for it to remain true

%
Progress

MEMORY METER
This indicates how strong in your memory this concept is
Progress
%
Evaluate Numerical and Variable Expressions Using the Order of Operations

### [Figure1] License: CC BY-NC 3.0

Jeb enters his name into a draw to win a handheld game system from his local electronics megastore. A week later he visits the store for the draw and his name is picked! In order to claim the prize, he must correctly answer a skill testing question.

The question is:

Jeb has to answer the skill testing question without the use of technology. How can Jeb answer this question correctly to claim the prize?

In this concept, you will learn to use the order of operations to solve numerical and variable expressions.

### Order of Operations

In mathematics, you will often hear the word evaluate. Before you begin, it is important for you to understand what the word evaluate means. When you evaluate a mathematical sentence, you figure out the value of the number sentence. Often times you think of evaluating as solving, and it can be that, but more specifically, evaluating is figuring out the value of a sentence.

In mathematics, you can evaluate different types of number sentences. Sometimes you will be working with equations and other times you will be working with expressions. First you need to know the difference between an equation and an expression.

An equation is a statement that two mathematical expressions have the same value. An equation has an equal sign such that the quantity on the left side of the equal sign is equal to the quantity on the right side of the equal sign. This means both sides of the equation stand for the same number.  is an equation. It states that  have the same value.

An expression is a general term in mathematics for a group of numbers, symbols and variables representing numbers and operations. You evaluate an expression to figure out the value of the mathematical statement itself, you are not trying to make one side equal another, as with an equation.  is an expression. There is no equal sign.

Two eighth grade math students evaluated the expression . Macy’s answer was ten and Cole’s answer was eight. The students you are asked to write their step by step solutions on the board.

Macy‘s Solution:

Cole‘s Solution:

It appears that each student performed the indicated operations in different orders. Of course, there cannot be two correct solutions for the same expression. There is actually a specific order in which operations must be performed.

The order of operations is a rule that tells you which operation you need to perform and the order in which it must be done to achieve the correct answer. The order of operations is often called PEMDAS and each of the letters represents one part of the rule. P: parenthesis and grouping symbols; E: exponents; M: multiplication; D: division; A: addition; S: subtraction. MD (multiplication and division) are performed in the order they appear in the expression from left to right. AS (addition and subtraction) are also performed in the order they appear in the expression from left to right.

Looking at the two solutions for evaluating the expression  who has the correct answer?

Macy

Cole

Macy evaluated the expression by performing the addition first, followed by multiplication and division. Cole performed the multiplication and division first, then addition. Macy simply completed the operations as they appeared from left to right. Cole completed the multiplication and division as they appeared from left to right and then performed the addition as his final step. Cole used the order of operations rule, PEMDAS, and his answer is correct.

This is called evaluating or simplifying a numerical expression. A numerical expression is an expression made up only of numbers and operations.

In addition to numbers, expressions can also have letters. The letters in an expression are called variables. These variables represent an unknown quantity. When an expression is written with a variable in it, you call it a variable expression.

A variable expression is evaluated using the order of operations in the same way as a numerical expression is evaluated. In this Concept there will be a value given for the variable and you will substitute it into the variable expression before evaluating the expression.

Evaluate the variable expression:

First, substitute the given value for  in the expression:

Remember that, used this way, parenthesis mean you are multiplying 2 times (5).

Now apply the order of operations (PEMDAS) and continue to evaluate the expression.

First, divide: and write the new expression.

Next, multiply:  since this is the first multiplication from left to right.

Next, multiply:  and write the new expression.

Next, add:  and write the new expression.

Then, subtract:

Now let’s add in the grouping symbols. The grouping symbols that you will be working with are brackets [  ] and parenthesis (  ). According to the order of operations (PEMDAS), you perform all operations inside the grouping symbols BEFORE any other operation in the list.

Evaluate the numerical expression

First, perform the operation in the parenthesis:  and write the new expression.

Next, multiply  to clear the parenthesis and write the new expression.

Next, add: and write the new expression.

Then, subtract:

Brackets can be used to group more than one operation. When you see a set of brackets, remember that brackets are a way of grouping numbers and operations with other groups already in parenthesis. Always evaluate grouping symbols from the innermost to the outermost.

Evaluate the numerical expression.

First, evaluate the innermost grouping symbols: the parenthesis.

Multiply: and write the new expression.

Next, perform the operation inside the brackets.

Add: and write the new expression.

Next, add: and write the new expression.

Then, subtract:

### Examples

#### Example 1

Earlier, you were given a problem about Jeb and his (almost) prize.

Remember, when solving a problem like this skill testing question, you need to complete the indicated operations in the order of PEMDAS.

Notice there are parenthesis within the brackets. You need to evaluate from the inside out. So start with the parenthesis. According to PEMDAS multiplication comes before subtraction, and this is just as true within a group as without.

First, multiply:  and write the new expression.

Next, subtract:   and write the new expression.

Next, subtract:   and write the new expression.

Next, multiply: and write the new expression.

Then, divide:

Jeb needs to answer 20 to claim his prize.

#### Example 2

Evaluate the expression

First, multiply  and write down the new expression.

Next, divide  and write down the new expression.

Next add  and write down the new expression.

#### Example 3

Evaluate the variable expression

First, substitute  into the expression.

Next, perform the operation inside the parenthesis.

Multiply:  and write the new expression.

Next, multiply:  to clear the parenthesis and write the new expression.

Next add:  and write the new expression.

Then, subtract:

#### Example 4

Evaluate the numerical expression.

Remember to evaluate the grouping symbols from the innermost to the outermost.

First, perform the operation inside the parenthesis.

Multiply:  and write the new expression.

Next, perform the operation inside the brackets.

Add:  and write the new expression.

Then multiply

Next, add:  and write the new expression.

Finally, subtract

#### Example 5

Evaluate the variable expression.

First substitute   into the expression.

First, multiply: and write the new expression.

Next, divide: and write the new expression.

Then, multiply again:  and write another new expression.

Next, add: and write the new expression.

Finally, subtract :

### Review

Evaluate each numerical expression using the order of operations.

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

Evaluate each variable expression. Remember to use PEMDAS when necessary.

11.

12.

13.

14.

15.

To see the Review answers, open this PDF file and look for section 1.4.

### Notes/Highlights Having trouble? Report an issue.

Color Highlighted Text Notes

### Vocabulary Language: English

Brackets

Brackets [ ], are symbols that are used to group numbers in mathematics. Brackets are the 'second level' of grouping symbols, used to enclose items already in parentheses.

Equation

An equation is a mathematical sentence that describes two equal quantities. Equations contain equals signs.

Evaluate

To evaluate an expression or equation means to perform the included operations, commonly in order to find a specific value.

Expression

An expression is a mathematical phrase containing variables, operations and/or numbers. Expressions do not include comparative operators such as equal signs or inequality symbols.

Grouping Symbols

Grouping symbols are parentheses or brackets used to group numbers and operations.

nested parentheses

Nested parentheses describe groups of terms inside of other groups. By convention, nested parentheses may be identified with other grouping symbols, such as the braces "{}" and brackets "[]" in the expression $\{ 3 + [ 2 - ( 5 + 4 ) ] \}$. Always evaluate parentheses from the innermost set outward.

Numerical expression

A numerical expression is a group of numbers and operations used to represent a quantity.

Parentheses

Parentheses "(" and ")" are used in algebraic expressions as grouping symbols.

PEMDAS

PEMDAS (Please Excuse My Daring Aunt Sally) is a mnemonic device used to help remember the order of operations: Parentheses, Exponents, Multiplication/Division, Addition/Subtraction.

Real Number

A real number is a number that can be plotted on a number line. Real numbers include all rational and irrational numbers.

Variable

A variable is a symbol used to represent an unknown or changing quantity. The most common variables are a, b, x, y, m, and n.

Variable Expression

A variable expression is a mathematical phrase that contains at least one variable or unknown quantity.