text:
# Logical Deduction: Practice Set - 3

Team of subject matter experts of JagranJosh have come up with all new Conceptual Practice Test on Logical Reasoning - Logical Deduction based on the topics like Eligibility Test, Statement Argument etc. This practice set contains 15 questions with explanations. Logical Reasoning - Logical Deduction Online Practice Test is useful for all important exams like IBPS, SBI PO-Clerk, IBPS RRB, SBI, Insurance, SSC, CAT, Railways, CDS, CTET, Campus Placements, etc.

• ## Question 1

A group of leading film-makers is seeking to dilute the strong tobacco control measures undertaken by successive governments. The film-makers have made a representation to the Information and Broadcasting Ministry to withdraw the stipulation that cinemas run a warning scroll whenever smoking scenes appear on screen. The argument that showing the scrolls in the manner it is done affects the creativity of the scenes is at best specious. Appearing at the bottom of the screen, the warning does not in any way affect any aspect of creativity. The World Health Organization has stated that the “implementation of a comprehensive ban on tobacco advertising and promotion should not prevent legitimate artistic expression”. But that cannot be an argument against the use of the warning scrolls during smoking scenes.
The author of the passage is in the favor of which of the following argument?
• ## Question 2

Payments by mobiles have grown from just 860 transactions in November 2010 to 4.4 million in August 2014. With the spread of Internet and expansion of e-commerce, online payments are fast catching on among the middle class. These are mostly cashless transactions.
Which of the following would strengthen the above argument?
• ## Question 3

Drug addiction, like other habits such as smoking and drinking, almost always begins under peer pressure with teenagers being influenced by those of their high school and college colleagues who are only slightly older to join the “gang” and become adults, so to say. Even if in the initial stages, those youngsters who have been induced to start taking drugs do not find it pleasurable, they are unwilling to break away lest they offend seniors.
Which of the following, if true, will most weaken the above argument?
• ## Question 4

The fact of the matter is that there is a strong case for increasing the farm subsidies, at least indirectly. The Indian farm sector is now passing through a difficult period, as underscored by the suicides of farmers reported from states like Maharashtra and Andhra.
Which of the following would strengthen the above argument?
• ## Question 5

In fiscal year ending June 2011, with a normal monsoon season, Indian agriculture accomplished an all-time record production of 85.9 million tonnes of wheat, a 6.4% increase from a year earlier.
Which of the following would strengthen the above argument?
• ## Question 6

“There has been a high incidence of death in Rajasthan due to tobacco eating last year”. Hence, the Rajasthan’s Chief Minister suggested that tax rates on dangerous tobacco products like cigarette and gutka should not to be reduced as planned by the government.
Which of the following, if true, will most weaken the above argument?
• ## Question 7

The impact of 1991 Economic Reforms may be gauged from the fact that total foreign investment (including foreign direct investment, portfolio investment, and investment raised on international capital markets) in India grew from a minuscule US$132 million in 1991–92 to$5.3 billion in 1995–96.
Which of the following would strengthen the above argument?
• ## Question 8

Direction: Study the following information carefully and answer the questions given below:
Following are the conditions for selecting Marketing Manager in an organization:
The candidate must
(i) be a graduate in any discipline with at least 55 per cent marks.
(ii) have a postgraduate degree/diploma in Marketing Management with at least 60 per cent marks.
(iii) have post-qualification work experience of at least five 'years in the marketing division of an organisation.
(iv) have secured at least 45 per. cent marks in the selection examination.
(v) have secured at least 40 per cent marks in the selection interview.
In the case of a candidate who satisfies all the conditions except
(a) at (iii) above, but has post-qualification work
experience of at least three years as Deputy Marketing Manager, the case is to be referred to GM-Marketing.
(b) at (v) above, but has secured at least 60 per cent marks in the selection examination, the case is to be referred to VP-Marketing.
In each question below, details of one candidate are given. You have to take one of the following courses of action based on the information provided and the conditions and sub-conditions given above and mark the number of that course of action as your answer. You are not to assume anything other than the information provided in each question. All these cases are given to you as on 01.05.2010.

Sadashiv Ghatge has secured 60 per cent marks in BCom. He has been working for the past five years in the marketing division of an organisation after completing his post- graduate degree in Marketing Management with 68% marks. He has secured 35 per cent marks in the selection interview and 62 per cent marks in the selection examination.
• ## Question 9

Direction: Study the following information carefully and answer the questions given below:
Following are the conditions for selecting Marketing Manager in an organization:
The candidate must
(i) be a graduate in any discipline with at least 55 per cent marks.
(ii) have a postgraduate degree/diploma in Marketing Management with at least 60 per cent marks.
(iii) have post-qualification work experience of at least five 'years in the marketing division of an organisation.
(iv) have secured at least 45 per. cent marks in the selection examination.
(v) have secured at least 40 per cent marks in the selection interview.
In the case of a candidate who satisfies all the conditions except
(a) at (iii) above, but has post-qualification work
experience of at least three years as Deputy Marketing Manager, the case is to be referred to GM-Marketing.
(b) at (v) above, but has secured at least 60 per cent marks in the selection examination, the case is to be referred to VP-Marketing.
In each question below, details of one candidate are given. You have to take one of the following courses of action based on the information provided and the conditions and sub-conditions given above and mark the number of that course of action as your answer. You are not to assume anything other than the information provided in each question. All these cases are given to you as on 01.05.2010.

Nimisha Patil has secured 59 per cent marks in BCom. She has also secured 50 per cent marks in both selection examination and the selection interview. She has been working as Deputy Marketing Manager in an organisation for the past three years after completing her postgraduate degree in Marketing Management with 63 per cent marks.
• ## Question 10

Direction: Study the following information carefully and answer the questions given below:
Following are the conditions for selecting Marketing Manager in an organization:
The candidate must
(i) be a graduate in any discipline with at least 55 per cent marks.
(ii) have a postgraduate degree/diploma in Marketing Management with at least 60 per cent marks.
(iii) have post-qualification work experience of at least five 'years in the marketing division of an organisation.
(iv) have secured at least 45 per. cent marks in the selection examination.
(v) have secured at least 40 per cent marks in the selection interview.
In the case of a candidate who satisfies all the conditions except
(a) at (iii) above, but has post-qualification work
experience of at least three years as Deputy Marketing Manager, the case is to be referred to GM-Marketing.
(b) at (v) above, but has secured at least 60 per cent marks in the selection examination, the case is to be referred to VP-Marketing.
In each question below, details of one candidate are given. You have to take one of the following courses of action based on the information provided and the conditions and sub-conditions given above and mark the number of that course of action as your answer. You are not to assume anything other than the information provided in each question. All these cases are given to you as on 01.05.2010.

Samir Phukan has been working in the marketing division of an organisation for the past five years after completing his post graduate diploma in management with 65 per cent marks. He has secured 60 per cent marks in BCom. He has also secured 50 per cent marks in both selection examination and selection interview.
• ## Question 11

Direction: Study the following information carefully and answer the questions given below:
Following are the conditions for selecting Marketing Manager in an organization:
The candidate must
(i) be a graduate in any discipline with at least 55 per cent marks.
(ii) have a postgraduate degree/diploma in Marketing Management with at least 60 per cent marks.
(iii) have post-qualification work experience of at least five 'years in the marketing division of an organisation.
(iv) have secured at least 45 per. cent marks in the selection examination.
(v) have secured at least 40 per cent marks in the selection interview.
In the case of a candidate who satisfies all the conditions except
(a) at (iii) above, but has post-qualification work
experience of at least three years as Deputy Marketing Manager, the case is to be referred to GM-Marketing.
(b) at (v) above, but has secured at least 60 per cent marks in the selection examination, the case is to be referred to VP-Marketing.
In each question below, details of one candidate are given. You have to take one of the following courses of action based on the information provided and the conditions and sub-conditions given above and mark the number of that course of action as your answer. You are not to assume anything other than the information provided in each question. All these cases are given to you as on 01.05.2010.

Anindita Ghosh has been working for the past eight years in an organisation after completing her postgraduate degree in Marketing Management with 70 per cent marks. She has secured 56 per cent marks in BA. She has also secured 50 per cent marks in the selection examination and 45 per cent marks in the selection interview.
• ## Question 12

Direction: Study the following information carefully and answer the questions given below:
Following are the conditions for selecting Marketing Manager in an organization:
The candidate must
(i) be a graduate in any discipline with at least 55 per cent marks.
(ii) have a postgraduate degree/diploma in Marketing Management with at least 60 per cent marks.
(iii) have post-qualification work experience of at least five 'years in the marketing division of an organisation.
(iv) have secured at least 45 per. cent marks in the selection examination.
(v) have secured at least 40 per cent marks in the selection interview.
In the case of a candidate who satisfies all the conditions except
(a) at (iii) above, but has post-qualification work
experience of at least three years as Deputy Marketing Manager, the case is to be referred to GM-Marketing.
(b) at (v) above, but has secured at least 60 per cent marks in the selection examination, the case is to be referred to VP-Marketing.
In each question below, details of one candidate are given. You have to take one of the following courses of action based on the information provided and the conditions and sub-conditions given above and mark the number of that course of action as your answer. You are not to assume anything other than the information provided in each question. All these cases are given to you as on 01.05.2010.

completing her postgraduation in Marketing Management with 57 per cent marks.
• ## Question 13

Direction: Study the following information carefully and answer the questions given below:
Following are the conditions for selecting Marketing Manager in an organization:
The candidate must
(i) be a graduate in any discipline with at least 55 per cent marks.
(ii) have a postgraduate degree/diploma in Marketing Management with at least 60 per cent marks.
(iii) have post-qualification work experience of at least five 'years in the marketing division of an organisation.
(iv) have secured at least 45 per. cent marks in the selection examination.
(v) have secured at least 40 per cent marks in the selection interview.
In the case of a candidate who satisfies all the conditions except
(a) at (iii) above, but has post-qualification work
experience of at least three years as Deputy Marketing Manager, the case is to be referred to GM-Marketing.
(b) at (v) above, but has secured at least 60 per cent marks in the selection examination, the case is to be referred to VP-Marketing.
In each question below, details of one candidate are given. You have to take one of the following courses of action based on the information provided and the conditions and sub-conditions given above and mark the number of that course of action as your answer. You are not to assume anything other than the information provided in each question. All these cases are given to you as on 01.05.2010.

Varsha Akolkar has secured 59 per cent marks in BA. She has secured 42 per cent marks in the selection interview and 48 per cent marks in the selection examination. She has been working in the marketing division of an organisation for the past seven years after completing her postgraduation in Marketing Management with 57 per cent marks.
• ## Question 14

Direction: Study the following information carefully and answer the questions given below:
Following are the conditions for selecting Marketing Manager in an organization:
The candidate must
(i) be a graduate in any discipline with at least 55 per cent marks.
(ii) have a postgraduate degree/diploma in Marketing Management with at least 60 per cent marks.
(iii) have post-qualification work experience of at least five 'years in the marketing division of an organisation.
(iv) have secured at least 45 per. cent marks in the selection examination.
(v) have secured at least 40 per cent marks in the selection interview.
In the case of a candidate who satisfies all the conditions except
(a) at (iii) above, but has post-qualification work
experience of at least three years as Deputy Marketing Manager, the case is to be referred to GM-Marketing.
(b) at (v) above, but has secured at least 60 per cent marks in the selection examination, the case is to be referred to VP-Marketing.
In each question below, details of one candidate are given. You have to take one of the following courses of action based on the information provided and the conditions and sub-conditions given above and mark the number of that course of action as your answer. You are not to assume anything other than the information provided in each question. All these cases are given to you as on 01.05.2010.

Manoj Malhotra has secured 65 per cent marks in BSc and 60 per cent marks in postgraduate degree in Marketing Management. He has also secured 50 per cent marks in both selection examination and selection interview, He has been working in the marketing division of an organisation for the past six years after completing his postgraduation in Marketing.
• ## Question 15

Direction: Study the following information carefully and answer the questions given below:
Following are the conditions for selecting Marketing Manager in an organization:
The candidate must
(i) be a graduate in any discipline with at least 55 per cent marks.
(ii) have a postgraduate degree/diploma in Marketing Management with at least 60 per cent marks.
(iii) have post-qualification work experience of at least five 'years in the marketing division of an organisation.
(iv) have secured at least 45 per. cent marks in the selection examination.
(v) have secured at least 40 per cent marks in the selection interview.
In the case of a candidate who satisfies all the conditions except
(a) at (iii) above, but has post-qualification work
experience of at least three years as Deputy Marketing Manager, the case is to be referred to GM-Marketing.
(b) at (v) above, but has secured at least 60 per cent marks in the selection examination, the case is to be referred to VP-Marketing.
In each question below, details of one candidate are given. You have to take one of the following courses of action based on the information provided and the conditions and sub-conditions given above and mark the number of that course of action as your answer. You are not to assume anything other than the information provided in each question. All these cases are given to you as on 01.05.2010.

Sabina Handa has been working for the past four years as Deputy Marketing Manager in an organisation after completing her postgraduate diploma in Marketing Management with 65 per cent marks. She has secured 45 percent marks in both selection examination and selection interview. She has also secured 58 per cent marks in BCom.


text:
# What is the derivative of (12/sinx) + (1/cotx)?

Sep 16, 2015

−12cosecx⋅cotx+sec^2x

#### Explanation:

1/$\sin x$ = $\cos e c x$ similarly $\frac{1}{\cot} x$ = $\tan x$
the question changes to $12 \cos e c x + \tan x$
the derivative is $- 12 \cos e c x \cdot \cot x + {\sec}^{2} x$ by (u/v rule of differentiation)
$\frac{d}{\mathrm{dx}}$ $\left(\frac{1}{\sin} x\right)$ = $\frac{1}{\sin} ^ 2 x$ $\left(- 1 \cdot \cos x\right)$
= $- \cos \frac{x}{\sin} x$ $\frac{1}{\sin} x$
=$- \cos e c x \cot x$
$\frac{d}{\mathrm{dx}}$ $\tan x$= $\frac{d}{\mathrm{dx}} \left(\sin \frac{x}{\cos} x\right)$
=$\frac{1}{\cos} ^ 2 x$ $\left(\cos x \cdot \cos x - \sin x \cdot \left(- \sin x\right)\right)$
=$\frac{{\cos}^{2} x + {\sin}^{2} x}{\cos} ^ 2 x$
=$\frac{1}{\cos} ^ 2 x$=${\sec}^{2} x$

format: plain


text:
# Workflow for submitting journal articles with Tikz figures

Submitted by winstead on Wed, 02/12/2014 - 07:15

### Forums:

When writing articles with LaTeX, I strongly encourage using Tikz for figures, and PGFplots for showing data curves. There are lots of advantages to using these packages, but sometimes journals are not prepared to accept all of your raw data and TikZ code. In the final stages of submission, you may need to translate your TikZ figures into PDF or EPS files so that they can be reliably processed by the publisher. Here is some advice for handling the conversion:

From the beginning, make sure your TikZ figures are well organized in external files. I usually create a directory called "figures" and place my plots and illustrations in that directory, with the "tikz" extension. Then in your main tex file, a typical figure declaration should look like this:

\begin{figure}[ht]
\centering
\input{figures/my_plot.tikz}
\label{fig:some label}
\caption{Here is some caption for my plot.}
\end{figure}

If you have prepared a complete article for submission to a journal, then there will probably be many such figures. To convert them to PDF files, use the preview package by placing these lines in your document preamble:

\usepackage[active,pdftex,tightpage,delayed]{preview}
\PreviewEnvironment{tikzpicture}

Now if you compile the document again, you will get a PDF file that contains only the Tikz figures. Use a program like pdfsam to split the PDF into individual figure files, and give them names like "fig1.pdf", "fig2.pdf" and so on. Place all of these files in the "figures" directory. Finally, for each figure in your latex file, make a change like this:

\begin{figure}[ht]
\centering
%\input{figures/my_plot.tikz}
\includegraphics[scale=1]{figures/fig1.pdf}
\label{fig:some label}
\caption{Here is some caption for my plot.}
\end{figure}

These changes need to be made carefully, one at a time, to replace the TikZ figure with the newly produced PDF version. After making the changes, recompile your document and verify that you got all the right figures in the right places. Your document should look exactly the same as the original version with the TikZ figures.

When making the final submission, prepare a "clean" version of your document directory, containing only the main tex file, the bibliography and the PDF figures. The journal editors don't want any extraneous files, just the ones needed to reproduce the final article.

These steps are usually only needed in the last stage or publication, after an article has passed peer review. I discovered today that this procedure was necessary to complete a pre-print submission at the arXiv, so I though it might be useful to post the procedure here.


text:
# find and correct the errors in the following mathematical statementsQ20)$\frac{4 x + 5 }{4x } = 5$

Our L.H.S. is $\Rightarrow \frac{4x+5}{4x} = \frac{4x}{4x} + \frac{5}{4x} = 1 + \frac{5}{4x} \neq$    R.H.S.
Correct statement is $\frac{4x+5}{4x} = 1 + \frac{5}{4x} = \frac{4x+5}{4x}$


text:
On completely Ramsey sets.(English)Zbl 0632.04005

We consider completely Ramsey sets. Our main result says that the union of less than $$\kappa (N^*)$$ of completely Ramsey sets is completely Ramsey and the union of $$\kappa (N^*)$$ of completely Ramsey sets can be a set which is not completely Ramsey.

MSC:

 3e+15 Descriptive set theory

Keywords:

completely Ramsey sets
Full Text:


text:
# Article

 Title: A representation of the coalgebra of derivations for smooth spaces (English) Author: Fischer, Gerald Language: English Journal: Proceedings of the 18th Winter School "Geometry and Physics" Volume: Issue: 1998 Year: Pages: 135-141 . Category: math . Summary: Let $K$ be a field. The generalized Leibniz rule for higher derivations suggests the definition of a coalgebra ${\cal D}^k_K$ for any positive integer $k$. This is spanned over $K$ by $d_0,\ldots,d_k$, and has comultiplication $\Delta$ and counit $\varepsilon$ defined by $\Delta(d_i)=\sum_{j=0}^id_j\otimes d_{i-j}$ and $\varepsilon(d_i)=\delta_{0,i}$ (Kronecker's delta) for any $i$. This note presents a representation of the coalgebra ${\cal D}^k_K$ by using smooth spaces and a procedure of microlocalization. The author gives an interpretation of this result following the principles of the quantum theory of geometric spaces. (English) MSC: 16W25 MSC: 16W30 MSC: 16W60 MSC: 32C38 idZBL: Zbl 0962.16027 idMR: MR1692264 . Date available: 2009-07-13T21:41:18Z Last updated: 2012-09-18 Stable URL: http://hdl.handle.net/10338.dmlcz/701632 .

## Files

Files Size Format View
WSGP_18-1998-1_11.pdf 371.3Kb application/pdf View/Open

Partner of


text:
## Recursive Binary Search

### 2020-08-15

Binary search is a search algorithm that operates on sorted sequences of data. This blog post will present one possible implementation of recursive binary search algorithm, walks through its details, and expresses the algorithm in C++.

Pseudocode for one possible recursive binary search algorithm is

\begin{algorithm}
\caption{\textsc{Binary-Search}$(A, key)$}
\begin{algorithmic}
\State $i = \lfloor A\text{.length} \ / \ 2 \rfloor$
\State $L = A[1 \ \ldots \ i]$
\State $R = A[i + 1 \ \ldots \ A\text{.length}]$
\If{ $key \ != A[i]$ }
\If{ $L\text{.length} == 0$ }
\Return $\infty$
\ElseIf{ $key < A[i]$ }
\Return \textsc{Binary-Search}($L, \ key$)
\Else
\Return \textsc{Binary-Search}($R, \ key$)
\EndIf
\Else
\Return $A[i]$
\EndIf
\end{algorithmic}
\end{algorithm}

where $$A$$ is assumed to be a partial order array, that is, an array satisfying the property, $A = \{ \ a_i \in A \ | \ a_1 \leq a_2 \leq \ldots \leq a_i \ \}$ and $$key$$ is a value to be searched from $$A$$.

Binary search begins by assigning a rounded down index value for variable $$i$$ that indexes middle of the argument array $$A$$, which is then split into left and right subarrays, named $$L$$ and $$R$$ respectively.

After initial setup, the reason of the algorithm is fulfilled at line $$4$$ when $$key$$ is tested with respect to value at $$A[i]$$. If the two terms are not equal, and length of $$A$$ is not zero, anew recursive query is done either into $$L$$ or $$R$$. The path chosen is dependant on whether the predicate $$key < A[i]$$ is true or not. That is, left subarray is searched if $$key$$ is less than value at $$A[i]$$, right otherwise.

Algorithm returns the value of positive infinity if $$key$$ is not in $$A$$. This return value was chosen, so that the algorithm can be used to construct further algorithmic expressions which evaluate numerical values rather than booleans.

Binary search as described above can be expressed in C++ as follows:

template <typename T>
T binary_search(const std::vector<T>& vector, const T& key)
{
T i = vector.size() / 2;
T candidate = vector.at(i);

std::vector<T> L {vector.begin(), vector.begin() + i},
R {vector.begin() + i, vector.end()};

if (key != candidate)
{
if (L.size() == 0)
return std::numeric_limits<T>::infinity;
else if (key < candidate)
return binary_search(L, key);
else
return binary_search(R, key);
}

else return candidate;
}

The program is syntactically identical to the presented algorithm, with the exception that $$A[i]$$ is being assigned into variable  candidate  in order to improve readability.

References:

Cormen, T. H., Leiserson, E. C., Rivest, R. L, and Stein, C. 2009. Introduction to algorithms. 3rd ed. Cambridge: The MIT Press.


text:
# Orbit sizes for irreducible representations may differ from orbit sizes for conjugacy classes under action of automorphism group

## Statement

It is possible to have a finite group $G$ with the property that under the action of the automorphism group $\operatorname{Aut}(G)$, the orbit sizes for the set $R(G)$ of irreducible linear representations of $G$ are not the same as the orbit sizes for the set $C(G)$ of conjugacy classes of $G$.

A finite group where the orbit sizes are in fact the same is termed a finite group having the same orbit sizes of conjugacy classes and irreducible representations under automorphism group.

## Related facts

### Opposite facts

This gives a sufficient condition for being a finite group having the same orbit sizes of conjugacy classes and irreducible representations under automorphism group. The following hold for all finite groups:

## Proof

There are examples of groups of order 27.


text:
Na-Rae Han (naraehan@pitt.edu), 5/30/2017, CMU DH Summer Workshop

# Preparation¶

Jupyter tips:

• Shift+ENTER to run cell, go to next cell
• Alt+ENTER to run cell, create a new cell below

# The very basics¶

### First code¶

• Printing a string, using print().
In [ ]:
print("hello, world!")

### The string type¶

• String type objects are enclosed in quotation marks.
• + is a concatenation operator.
• Below, greet is a variable name assigned to a string value; note the absence of quotation marks.
In [ ]:
greet = "Hello, world!"
greet + " I come in peace."

• String methods such as .upper(), .lower() transform a string.
In [ ]:
greet.upper()

• len() returns the length of a string in the # of characters.
In [ ]:
len(greet)

### Numbers¶

• Integers and floats are written without quotes.
• You can use algebraic operations such as +, -, * and / with numbers.
In [ ]:
num1 = 5678
num2 = 3.141592
result = num1 / num2
print(num1, "divided by", str(num2), "is", result)

### Lists¶

• Lists are enclosed in [ ], with elements separated with commas. Lists can have strings, numbers, and more.
• Like with string, you can use len() to get the size of a list.
• Like with string, you can use in to see if an element is in a list.
• A list can be indexed through li[i]. Python indexes starts with 0.
• A list can be sliced: li[3:5] returns a sub-list beginning with index 3 up to and not including index 5.
In [ ]:
li = ['red', 'blue', 'green', 'black', 'white', 'pink']
len(li)

In [ ]:
'mauve' not in li

In [ ]:
# Try [0], [2], [-1], [3:5], [3:], [:5]
li[0]

### for loop¶

• Using for loop, you can loop through a list of items, applying the same set of operations to each element.
• The embedded code block is marked with indentation.
In [ ]:
for x in li :
print(x, len(x))
print("Done!")

### List comprehension¶

• List comprehension builds a new list from an existing list.
• You can filter in only certain elements, and you can apply transformation in the process.
• Try: .upper(), len(), +'ish'
In [ ]:
[x for x in li if x.endswith('e')]

In [ ]:
[x+'ish' for x in li]

In [ ]:
[len(x) for x in li]

### Dictionaries¶

• Dictionaries hold key:value mappings.
• len() on dictionary returns the number of keys.
In [ ]:
di = {'Homer':35, 'Marge':35, 'Bart':10, 'Lisa':8}
di['Homer']

In [ ]:
len(di)

# Using NLTK¶

• NLTK is an external module; you can start using it after importing it.

• nltk.word_tokenize() is a handy tokenizing function out of literally tons of functions it provides.

• It turns a text (a single string) into a list tokenized words.

In [ ]:
import nltk

In [ ]:
nltk.word_tokenize(greet)

In [ ]:
help(nltk.word_tokenize)

In [ ]:
sent = "You haven't seen Star Wars...?"
nltk.word_tokenize(sent)

• nltk.FreqDist() is is another useful NLTK function.
• It builds a frequency dictionary from a list.
In [ ]:
# First "Rose" is capitalized. How to lowercase?
sent = 'Rose is a rose is a rose is a rose.'
toks = nltk.word_tokenize(sent)
print(toks)

In [ ]:
freq = nltk.FreqDist(toks)
freq

In [ ]:
freq.most_common(3)

In [ ]:
freq['rose']

In [ ]:
len(freq)

# Processing a single text file¶

### Reading in a text file¶

• open(filename).read() reads in the content of a text file as a single string.
In [ ]:
myfile = 'C:/Users/zoso/Desktop/inaugural/1789-Washington.txt'  # Mac users should leave out C:
print(wtxt)

In [ ]:
len(wtxt)     # Number of characters in text

In [ ]:
'fellow citizens'.lower() in wtxt.lower()  # phrase as a substring

In [ ]:
'Americans' in wtxt

### Tokenize text, compile frequency count¶

In [ ]:
# Turn off/on pretty printing (prints too many lines)
%pprint

In [ ]:
# Tokenize text
nltk.word_tokenize(wtxt)

In [ ]:
wtokens = nltk.word_tokenize(wtxt)
len(wtokens)     # Number of words in text

In [ ]:
# Build a dictionary of frequency count
wfreq = nltk.FreqDist(wtokens)
wfreq['citizens']

In [ ]:
wfreq['the']

In [ ]:
len(wfreq)      # Number of unique words in text

In [ ]:
wfreq.most_common(40)     # 40 most common words

### Average sentence length, frequency of long words¶

In [ ]:
sentcount = wfreq['.'] + wfreq['?'] + wfreq['!']  # Assuming every sentence ends with ., ! or
print(sentcount)

In [ ]:
# Tokens include symbols and punctuation. First 50 tokens:
wtokens[:50]

In [ ]:
wtokens_nosym = [t for t in wtokens if t.isalnum()]    # alpha-numeric tokens only
len(wtokens_nosym)

In [ ]:
# First 50 tokens, alpha-numeric tokens only:
wtokens_nosym[:50]

In [ ]:
len(wtokens_nosym)/sentcount     # Average sentence length in number of words

In [ ]:
[w for w in wfreq if len(w) >= 13]       # all 13+ character words

In [ ]:
long = [w for w in wfreq if len(w) >= 13]
for w in long :
print(w, len(w), wfreq[w])               # long words tend to be less frequent

# Processing a corpus¶

• NLTK can read in an entire corpus from a directory (the 'root' directory).
• As it reads in a corpus, it applies word tokenization (shown below) and sentence tokenization (not shown here).
In [ ]:
from nltk.corpus import PlaintextCorpusReader
corpus_root = 'C:/Users/zoso/Desktop/inaugural'  # Mac users should leave out C:
inaug = PlaintextCorpusReader(corpus_root, '.*txt')  # all files ending in 'txt'

In [ ]:
# .txt file names as file IDs
inaug.fileids()

In [ ]:
# NLTK automatically tokenizes the corpus. First 50 words:
print(inaug.words()[:50])

In [ ]:
# You can also specify individual file ID. First 50 words from Obama 2009:
print(inaug.words('2009-Obama.txt')[50:])

In [ ]:
# NLTK automatically segments sentences too, which are accessed through .sents()
print(inaug.sents('2009-Obama.txt')[0])   # first sentence
print(inaug.sents('2009-Obama.txt')[1])   # 2nd sentence

In [ ]:
# How long are these speeches in terms of word and sentence count?
print('Washington 1789:', len(inaug.words('1789-Washington.txt')), len(inaug.sents('1789-Washington.txt')))
print('Obama 2009:', len(inaug.words('2009-Obama.txt')), len(inaug.sents('2009-Obama.txt')))

In [ ]:
# for-loop through file IDs and print out word count.
for f in inaug.fileids():
print(len(inaug.words(f)), f)

### Trouble shooting¶

• Unfortunately, 2005 Bush file produces Unicode encoding error.
• Let's make a new text file from http://www.presidency.ucsb.edu/inaugurals.php
• Copy text and paste in Notepad (Windows). Make sure to choose UTF-8 encoding and not ANSI.
• The text files are locked; We will need to save, halt and then re-start the Python notebook.
In [ ]:
# Corpus size in number of words
print(len(inaug.words()))

In [ ]:
# Building word frequency distribution for the entire corpus
inaug_freq = nltk.FreqDist(inaug.words())
inaug_freq.most_common(100)

# What next?¶

Take a Python course!


text:
Statistics

7.2The Central Limit Theorem for Sums (Optional)

Statistics7.2 The Central Limit Theorem for Sums (Optional)

Suppose X is a random variable with a distribution that may be known or unknown (it can be any distribution) and suppose:

1. μX = the mean of Χ
2. σΧ = the standard deviation of X

If you draw random samples of size n, then as n increases, the random variable ΣX consisting of sums tends to be normally distributed and ΣΧ ~ N[(n)(μΧ), ($n n$)(σΧ)].

The central limit theorem for sums says that if you keep drawing larger and larger samples and taking their sums, the sums form their own normal distribution (the sampling distribution), which approaches a normal distribution as the sample size increases. The normal distribution has a mean equal to the original mean multiplied by the sample size and a standard deviation equal to the original standard deviation multiplied by the square root of the sample size.

The random variable ΣX has the following z-score associated with it:

1. Σx is one sum.
1. (n)(μX) = mean of ΣX
2. $( n )( σ X ) ( n )( σ X )$ = standard deviation of $ΣX ΣX$

Using the TI-83, 83+, 84, 84+ Calculator

To find probabilities for sums on the calculator, follow these steps:

2nd DISTR
2:normalcdf
normalcdf(lower value of the area, upper value of the area, (n)(mean), ($n n$)(standard deviation))

where,

• mean is the mean of the original distribution,
• standard deviation is the standard deviation of the original distribution, and
• sample size = n.

Example 7.5

An unknown distribution has a mean of 90 and a standard deviation of 15. A sample of size 80 is drawn randomly from the population.

1. Find the probability that the sum of the 80 values (or the total of the 80 values) is more than 7,500.
2. Find the sum that is 1.5 standard deviations above the mean of the sums.
Try It 7.5

An unknown distribution has a mean of 45 and a standard deviation of 8. A sample size of 50 is drawn randomly from the population. Find the probability that the sum of the 50 values is more than 2,400.

Using the TI-83, 83+, 84, 84+ Calculator

To find percentiles for sums on the calculator, follow these steps:

2nd DIStR
3:invNorm
k = invNorm (area to the left of k, (n)(mean), $( n ) ( n )$(standard deviation))

where,

• k is the kth percentile,
• mean is the mean of the original distribution,
• standard deviation is the standard deviation of the original distribution, and
• sample size = n.

Example 7.6

In a recent study reported Oct. 29, 2012, the mean age of tablet users is 34 years. Suppose the standard deviation is 15 years. The sample size is 50.

1. What are the mean and standard deviation for the sum of the ages of tablet users? What is the distribution?
2. Find the probability that the sum of the ages is between 1,500 and 1,800 years.
3. Find the 80th percentile for the sum of the 50 ages.
Try It 7.6

In a recent study reported Oct.29, 2012, the mean age of tablet users is 35 years. Suppose the standard deviation is 10 years. The sample size is 39.

1. What are the mean and standard deviation for the sum of the ages of tablet users? What is the distribution?
2. Find the probability that the sum of the ages is between 1,400 and 1,500 years.
3. Find the 90th percentile for the sum of the 39 ages.

Example 7.7

The mean number of minutes for app engagement by a tablet user is 8.2 minutes. Suppose the standard deviation is one minute. Take a sample size of 70.

1. What are the mean and standard deviation for the sums?
2. Find the 95th percentile for the sum of the sample. Interpret this value in a complete sentence.
3. Find the probability that the sum of the sample is at least 10 hours.
Try It 7.7

The mean number of minutes for app engagement by a tablet user is 8.2 minutes. Suppose the standard deviation is one minute. Take a sample size of 70.

1. What is the probability that the sum of the sample is between seven hours and 10 hours? What does this mean in context of the problem?
2. Find the 84th and 16th percentiles for the sum of the sample. Interpret these values in context.


text:
What is inside a black hole?

1. May 20, 2013

backward

I have a basic question.
It is well known that according to "our" time (time measured by an observer in flat space-time), an object falling into a black hole will never cross the event horizon (though, of course, according to its "proper time" it will fall into the singularity in a finite time) on account of time dilation near the black hole.
So, can we say that since the beginning of the universe, nothing has ever crossed over inside any black hole in "our" time. All events beyond the event horizon are in the future of "our" time, which may be infinite?

2. May 20, 2013

phinds

"Our" time is an optical illusion and not meaningful in terms of what happens locally. I think you already get this, so what's your point?

3. May 20, 2013

Simon Bridge

Welcome to PF;
I managed to tie myself in knots in this one too ...

I think there are a lot of misunderstandings evident in what you wrote - but I'll just go right to the nub of your question and maybe tackle these later (or someone else will).

By "inside" you mean, "within the radius of the event horizon"?
You want to know what happens as an object approaches a black hole from the point of view of an observer far from the hole, but stationary wrt the hole's center of mass?

It's tricky.

Oversimplifying: the effect is that the event horizon expands to enclose an object that approaches close enough. Recall that the radius of the event horizon depends on the mass inside. So something need only get close enough to within where the new event horizon is going to be to get "caught".

Now I just know that some people are going to take great exception to this description (I know I'm wincing a bit) :D
I'd love to see a better way of describing it myself so, like you, I wait.

 had a look for the place I got this impression from and cannot find it quickly ... suspect I got something horribly wrong <braces self>

Last edited: May 20, 2013
4. May 20, 2013

WannabeNewton

Coordinate time is a physically meaningless quantity. When speaking of elapsed times between events the only meaningful quantity is the proper time and for this there is only a finite amount needed for the in-falling observer to cross the event horizon. Phinds has already noted this above. You can make a judicious choice of coordinates and eliminate the coordinate singularity at the event horizon.

5. May 21, 2013

backward

"Our" time is an optical illusion and not meaningful in terms of what happens locally

I agree that in terms of what happens locally, "our time" is an illsion. But, at the same time, it is more or less (neglecting local motions of earth, sun, Galaxy and local galactic supercluster etc.) it is the cosmic time depending only on the scaler factor. It is the only absolute time that can be measured anywhere in the universe. Moroever, it is the time that we perceive. Proper time is not "our" time unless we are falling into the black hole, in which case what we perceive or experience is unlikely to be available to the media.

My point is precisely this:
So, can we say that since the beginning of the universe, nothing has ever crossed over inside any black hole in "our" time. All events beyond the event horizon are in the future of "our" time, which may be infinite?

Well it amuses me, so I thought I would invite reactions.

6. May 21, 2013

WannabeNewton

Again, you can eliminate the coordinate singularity with a change of coordinates (see Kruskal–Szekeres coordinates) so I still don't see your point. You are also mixing up different solutions to Einstein's equation; cosmic time refers to the "time-like coordinate" of the preferred coordinate system of the FRW metric describing the universe - it isn't referring to "time-like coordinate" of a Schwarzschild black hole solution.

7. May 21, 2013

skeptic2

What are the Kruskal–Szekeres coordinates at r = 2GM?

8. May 21, 2013

WannabeNewton

9. May 21, 2013

skeptic2

Assume that I, and possibly other readers, don't understand what any of that means. Can you please solve the appropriate equations for r = 2GM and provide us values for V and U with r = 2GM?

10. May 21, 2013

micromass

Staff Emeritus
Just plug in $r=2GM$ in the equations?

11. May 21, 2013

skeptic2

As I said, assume that I don't know how to solve them.

12. May 21, 2013

micromass

Staff Emeritus
There is nothing to solve... Just plug in $r=2GM$ in the definitions. This is just basic algebra.

13. May 21, 2013

WannabeNewton

Solve what? You asked what happens to the coordinates at $r = 2GM$. Just take the limit as $r$ approaches $2GM$ in the metric components given in the wiki article.

14. May 21, 2013

Spourk

No.

If your friend Fred "fell" (past tense) into a blackhole and is perpetually red shifted at the EH, he still fell into the black hole for both of you. The photons bouncing off his poor spagettified self right before falling in are just stuck there, so all your seeing is an illusion. An afterimage of the photons still stuck just above the surface of the EH.

If you want to speculate that the image of your friend is actually him just stuck in time on the edge of an EH, you might as well speculate that we live in a fish tank as well. (Just because you can't touch the edge of the fish tank doesn't mean it's real, right?)

15. May 22, 2013

backward

Thanks everybody. The inputs have been very valuable for me and I understand all the facts clearly.

16. May 28, 2013

Ron Bert

Hi Simon, thanks for your pleasant correspondence. I did review the link you supplied and though much surpasses my abilities, the information concerning black holes was very useful for myself and all who would be interested. Might I inquire of you a few questions as I hope you have the ability to respond appropriately, and it would help clarify my understanding.

Do I understand correctly that you believe that there is no actual singularity, as it is only a theoretical construct?

Do you believe there is no point without mass inside the black hole?

Am I correct in assuming that black holes maintain different diameters in relation to the event horizon and that they can grow and shrink?

If singularities exist, are not all singularities universally equivalent?

Could you elaborate on the map verses the territory?

Thanks again for any and all of your efforts.

17. May 28, 2013

WannabeNewton

There are different ways to define a singularity. The most intuitive (but not fully accurate) way is to use the concept of time-like or null geodesic incompleteness. If a space-time contains a time-like or null geodesic that is inextensible in a certain direction (e.g. there exists a massive particle that ends its existence in finite proper time) then there will be a physical singularity in the space-time. The singularities won't actually be points in space-time; you can imagine that one has removed the singularity and a "hole" has been left in place. The problem is that the singularity theorems of GR provide no information on the actual nature of these singularities so they are not currently explained by GR; all GR can do is prove that these singularities exist.

I'm not sure what you mean by this because the only mass parameter involved in characterizing a black hole is the mass of the black hole itself.

The area of the event horizon of a stationary black hole can increase as the black hole's mass increases. The relationship is given by the 1st law of black hole mechanics (the area can never decrease as a result of a physical process if the null energy condition holds, this is the 2nd law of black hole mechanics).

No, there are different kinds of singularities. For example, even amongst black holes there exist point-like singularities as well as ring singularities depending on if you are talking about static vs. rotating black holes. Things can get more abstract and pathological but there is no need to go there.

18. May 28, 2013

phinds

Ron, Simon is being very generous. What he sees as poetic, I see as meaningless blather. You should read the rules. Unsubstantiated personal opinion is one of the things the rules talks about (prohibited). This is a physics forum, not a forum for poetry or blather.

EDIT: this was a response to your post #16. I missed #18 and #19 and I see that you are not on the way to getting your facts straight. Still, my comments hold.

FURTHER EDIT: I now see that Ron's original post and Simon's response have both been removed, making my comment about it here look strange, and changing the post #s.

Last edited: May 28, 2013
19. May 28, 2013

phinds

"Singlarity" just means "the place where our model breaks down". Models don't all break down in the same way. Also, "singularity" does NOT mean "point".

The universe, in our most common model, is said to have started with a singularity and black holes are said to contain a singularity. These have nothing to do with each other except for the arbitrarily applied name.

20. May 28, 2013

Simon Bridge

Just quickly - the link I gave you is a good starting place, you can google the bits that you don't understand.

I know for a fact that it is an artifact of the model being used ... the same way I know the model spitfire hanging from the ceiling is made of plastic. There is no reason to suppose that the models we use are accurate in absolutely every detail so we have to be careful about how far we take them.

When the observer is closer than the Schwarzschild radius, there is no reason to believe that anything much will be different. But there is also no reason to believe that all the mass/energy is physically compressed to zero size either.

"maintain"?
It is reasonable to expect that the collapsed body within the event horizon has a different diameter to the horizon if that is what you mean.

However, you have to be careful with such glib statements - a lot of our intuitive concepts don't mean anything in these sorts of geometries.

No. No more than all infinities being the same.

"The map is not the territory."
-- Alfred Korzybski (Science and Sanity, 1933, p. 747–61)

The map–territory relation describes the relationship between an object and a representation of that object, as in the relation between a geographical territory and a map of it. "The map is not the territory", encapsulates the view that an abstraction derived from something, or a reaction to it, is not the thing itself. Many people do confuse maps with territories, that is, confuse models of reality with reality itself.

"I pointed the Way and you fell down on your knees and worshipped my finger."
-- Malaclypse the Elder (Principia Discordia)

In this case the Einstein relations for gravitation are the map.
Insisting on the physical reality for any result of these relations without checking them is to confuse the map for the territory. The map is always provisional.


text:
Set Theory Proof

Anushkaspam

New member
Prove f(a1∩f^-1(b2)=f(a1)∩b2

HallsofIvy

Elite Member
You missed a parenthesis- I think you mean f(a1)∩f^-1(b2)=f(a1)∩b2.
But now I have a problem with the domain and range of f. In order that the left side be non-empty there must be x that is in both f(a1) and in f^-1(b2). a1 must be a subset of the domain of f so f(x) is in the range of f. But b2 must be a subset of the range of f so that f^-1(x) is in the domain of f. That is, f must map some set onto itself.

Dr.Peterson

Elite Member
Prove f(a1)∩f^-1(b2)=f(a1)∩b2
This is not a complete statement of the problem. Please state everything; I expect to see something like this:

Prove that, for any function f:A -> A, and any subsets a1 and b1 of A, f(a1)∩f-1(b2)=f(a1)∩b2.


text:
# Is a sample covariance matrix always symmetric and positive definite?

When computing the covariance matrix of a sample, is one then guaranteed to get a symmetric and positive-definite matrix?

Currently my problem has a sample of 4600 observation vectors and 24 dimensions.

• For sampling the covariance matrix I use the formula: $Q_n = \frac{1}{n} \sum\limits_{i=1}^n (x_i-\bar{x})(x_i-\bar{x})^\top$ where $n$ is the number of samples and $\bar{x}$ is the sample mean. – Morten Mar 23 '13 at 10:00
• That would normally be called 'calculating the sample covariance matrix', or 'estimating the covariance matrix' rather than 'sampling the covariance matrix'. – Glen_b -Reinstate Monica Mar 23 '13 at 10:13
• A common situation in which the covariance matrix is not definite is when the 24 "dimensions" record the composition of a mixture that sums to 100%. – whuber Jul 11 '17 at 22:35

For a sample of vectors $$x_i=(x_{i1},\dots,x_{ik})^\top$$, with $$i=1,\dots,n$$, the sample mean vector is $$\bar{x}=\frac{1}{n} \sum_{i=1}^n x_i \, ,$$ and the sample covariance matrix is $$Q = \frac{1}{n} \sum_{i=1}^n (x_i-\bar{x})(x_i-\bar{x})^\top \, .$$ For a nonzero vector $$y\in\mathbb{R}^k$$, we have $$y^\top Qy = y^\top\left(\frac{1}{n} \sum_{i=1}^n (x_i-\bar{x})(x_i-\bar{x})^\top\right) y$$ $$= \frac{1}{n} \sum_{i=1}^n y^\top (x_i-\bar{x})(x_i-\bar{x})^\top y$$ $$= \frac{1}{n} \sum_{i=1}^n \left( (x_i-\bar{x})^\top y \right)^2 \geq 0 \, . \quad (*)$$ Therefore, $$Q$$ is always positive semi-definite.

The additional condition for $$Q$$ to be positive definite was given in whuber's comment bellow. It goes as follows.

Define $$z_i=(x_i-\bar{x})$$, for $$i=1,\dots,n$$. For any nonzero $$y\in\mathbb{R}^k$$, $$(*)$$ is zero if and only if $$z_i^\top y=0$$, for each $$i=1,\dots,n$$. Suppose the set $$\{z_1,\dots,z_n\}$$ spans $$\mathbb{R}^k$$. Then, there are real numbers $$\alpha_1,\dots,\alpha_n$$ such that $$y=\alpha_1 z_1 +\dots+\alpha_n z_n$$. But then we have $$y^\top y=\alpha_1 z_1^\top y + \dots +\alpha_n z_n^\top y=0$$, yielding that $$y=0$$, a contradiction. Hence, if the $$z_i$$'s span $$\mathbb{R}^k$$, then $$Q$$ is positive definite. This condition is equivalent to $$\mathrm{rank} [z_1 \dots z_n] = k$$.

• I like this approach, but would advise some care: $Q$ is not necessarily positive definite. The (necessary and sufficient) conditions for it to be so are described in my comment to Konstantin's answer. – whuber Mar 24 '13 at 3:26
• Since the rank of $[z_1, z_2, \cdots, z_n]$ is less or equal to $k$, the condition can be simplified to the rank is equal to k. – an offer can't refuse Nov 6 '18 at 15:43

A correct covariance matrix is always symmetric and positive *semi*definite.

The covariance between two variables is defied as $\sigma(x,y) = E [(x-E(x))(y-E(y))]$.

This equation doesn't change if you switch the positions of $x$ and $y$. Hence the matrix has to be symmetric.

It also has to be positive *semi-*definite because:

You can always find a transformation of your variables in a way that the covariance-matrix becomes diagonal. On the diagonal, you find the variances of your transformed variables which are either zero or positive, it is easy to see that this makes the transformed matrix positive semidefinite. However, since the definition of definity is transformation-invariant, it follows that the covariance-matrix is positive semidefinite in any chosen coordinate system.

When you estimate your covariance matrix (that is, when you calculate your sample covariance) with the formula you stated above, it will obv. still be symmetric. It also has to be positive semidefinite (I think), because for each sample, the pdf that gives each sample point equal probability has the sample covariance as its covariance (somebody please verify this), so everything stated above still applies.

• PS: I am starting to think that this wasn't your question... – Konstantin Schubert Mar 22 '13 at 13:53
• But if you want to know whether your sampling algorithm guarantees it, you will have to state how you are sampling. – Konstantin Schubert Mar 22 '13 at 15:19
• Morten, the symmetry is immediate from the formula. To show semi-definiteness, you need to establish that $uQ_nu'\ge 0$ for any vector $u$. But $Q_n$ is $1/n$ times a sum of $v_iv_i'$ (where $v_i=x_i-\bar{x})$, whence $n uQ_nu'$ is a sum of $u(v_iv_i')u'$ = $(uv_i)(uv_i)'$, which is the squared length of the vector $uv_i$. Because $n\gt 0$ and a sum of squares cannot ever be negative, $uQ_nu'\ge 0$, QED. This also shows that $uQ_nu'=0$ precisely for those vectors $u$ which are orthogonal to all the $v_i$ (i.e., $uv_i=0$ for all $i$). When the $v_i$ span, then $u=0$ and $Q_n$ is definite. – whuber Mar 23 '13 at 16:21
• @Morten The transformation-invariance is pretty clear if you understand a matrix multiplication geometrically. Think of your vector as an arrow. The numbers that describe your vector change with the coordinate system, but the direction and length of your vector doesnt. Now, a multiplication with a matrix means that you change length and direction of that arrow, but again the effect is geometrically the same in each coordinate system. The same is with a scalar product: It is defined geometrically and Geometriy is transformation-invariant. So your equation has the same result in all systems. – Konstantin Schubert Mar 23 '13 at 22:09
• @Morten When you think in coordinates, the argument goes like this: When $A$ is your transformation matrix then: $v'=Av$ with $v'$ as the transformed coordinate-vector, $M'=AMA^T$, so when you transform each element in the equation $v^T M v > 0$, you get $v'^T M' v' = (Av)^T A M A^T A v > 0$, which equals $v^T A^T A M A^T A v > 0$, and, because A is orthogonal, $A^T A$ is the unit matrix and we again get $v^T M v > 0$, which means that the transformed and the untransformed equation have the same scalar as result, so their are either both or both not greater zero. – Konstantin Schubert Mar 23 '13 at 22:17

Variance-Covariance matrices are always symmetric, as it can be proven from the actual equation to calculate each term of said matrix.

Also, Variance-Covariance matrices are always square matrices of size n, where n is the number of variables in your experiment.

Eigenvectors of symmetric matrices are always orthogonal.

With PCA, you determine the eigenvalues of the matrix to see if you could reduce the number of variables used in your experiment.

• Welcome Gen. Note that your username, identicon, & a link to your user page are automatically added to every post you make, so there is no need to sign your posts. – Antoine Vernet Jul 5 '16 at 14:38
• This answer could be improved by addressing the issue of positive definiteness – Silverfish Jul 5 '16 at 14:45
• This doesn't really answer the question: it's just a collection of unsupported assertions that might or might not be relevant. Could you reframe it in a way that shows how the question is answered and explains the reasoning? – whuber Jul 5 '16 at 15:01

I would add to the nice argument of Zen the following which explains why we often say that the covariance matrix is positive definite if $n-1\geq k$.

If $x_1,x_2,...,x_n$ are a random sample of a continuous probability distribution then $x_1,x_2,...,x_n$ are almost surely (in the probability theory sense) linearly independent. Now, $z_1,z_2,...,z_n$ are not linearly independent because $\sum_{i=1}^n z_i = 0$, but because of $x_1,x_2,...,x_n$ being a.s. linearly independent, $z_1,z_2,...,z_n$ a.s. span $\mathbb{R}^{n-1}$. If $n-1\geq k$, they also span $\mathbb{R}^k$.

To conclude, if $x_1,x_2,...,x_n$ are a random sample of a continuous probability distribution and $n-1\geq k$, the covariance matrix is positive definite.

For those with a non-mathematical background like me who don't quickly catch the abstract mathematical formulae, this is a worked out example excel for the most upvoted answer. The covariance matrix can be derived in other ways also.

• Could you explain how this spreadsheet demonstrates positive-definiteness of the covariance matrix? – whuber Jun 26 '19 at 15:12
• It does not. I had a hard time visualizing the covariance matrix in its notational form itself. So i created this sheet for myself and thought it could help someone. – Parikshit Bhinde Jun 27 '19 at 12:19
• Please, then, edit it to include an answer to the question. – whuber Jun 27 '19 at 12:38
• The question is "is one then guaranteed to get a symmetric and positive-definite matrix?" I am unable to perceive any element of your post that addresses this, because (1) it never identifies a covariance matrix; (2) it does not demonstrate positive-definiteness of anything. – whuber Jun 28 '19 at 12:55
• The formula you quote does not seem related to covariance or to the question. Also, your use of a $3\times 3$ matrix seems unconnected with whatever "$i=1$" might mean. The complete lack of any explanation in your post makes it difficult to interpret and quite confusing. – whuber Jun 28 '19 at 19:26


text:
# Internal documentation

This page documents the internal types and methods of Manifolds.jl's that might be of use for writing your own manifold.

## Types

Manifolds.SizedAbstractArrayType
SizedAbstractArray{Tuple{dims...}}(array)

Wraps an AbstractArray with a static size, so to take advantage of the (faster) methods defined by the static array package. The size is checked once upon construction to determine if the number of elements (length) match, but the array may be reshaped.

source

## Functions

Manifolds._gradientFunction
_gradient(f, p::Number, backend = adbackend()) -> Number
_gradient(f, p::Array, backend = adbackend()) -> Array

Compute gradient of function f at x using AD backend backend.

source
Manifolds._jacobianFunction
_jacobian(f, p, backend = adbackend()) -> Array

Compute Jacobian matrix of function f at p using AD backend backend. Inputs and outputs of f are vectorized.

source
Manifolds.eigen_safeFunction
eigen_safe(x)

Compute the eigendecomposition of x. If x is a StaticMatrix, it is converted to a Matrix before the decomposition.

source
Manifolds.find_pvFunction
find_pv(x...)

A = find_pv(x...) returns the first ProductArray among the arguments.

source
Manifolds.log_safeFunction
log_safe(x)

Compute the matrix logarithm of x. If x is a StaticMatrix, it is converted to a Matrix before computing the log.

source
Manifolds.size_to_tupleFunction
size_to_tuple(::Type{S}) where S<:Tuple

Converts a size given by Tuple{N, M, ...} into a tuple (N, M, ...).

source
Manifolds.select_from_tupleFunction
select_from_tuple(t::NTuple{N, Any}, positions::Val{P})

Selects elements of tuple t at positions specified by the second argument. For example select_from_tuple(("a", "b", "c"), Val((3, 1, 1))) returns ("c", "a", "a").

source
Manifolds.usincFunction
usinc(θ::Real)

Unnormalized version of sinc function, i.e. $\operatorname{usinc}(θ) = \frac{\sin(θ)}{θ}$. This is equivalent to sinc(θ/π).

source
Manifolds.usinc_from_cosFunction
usinc_from_cos(x::Real)

Unnormalized version of sinc function, i.e. $\operatorname{usinc}(θ) = \frac{\sin(θ)}{θ}$, computed from $x = cos(θ)$.

source
Manifolds.ziptuplesFunction
ziptuples(a, b[, c[, d[, e]]])

Zips tuples a, b, and remaining in a fast, type-stable way. If they have different lengths, the result is trimmed to the length of the shorter tuple.

source


text:
You might also need to add FORCE_SCRIPT_NAME setting to keep the url prefix of the original request.
The ASKBOT_URL is used in the urls.py file and is needed for the routing as well as for the correct result of reverse() calls - so that all urls printed in the html output have the prefix.


text:
0 votes
171 views

The perimeters of a circle, a square and an equilateral triangle are equal. Which one of the following statements is true?

1. The circle has the largest area
2. The square has the largest area
3. The equilateral triangle has the largest area
4. All the three shapes have the same area

recategorized | 171 views
Migrated from GO Mechanical 5 months ago by Arjun

## 2 Answers

0 votes
Best answer
For a given perimeter circle has the largest area.

Similarly, for a given surface area, a cube has the largest volume.

So, correct answer: A
by Veteran (422k points)
+1

@Arjun sir,

For given surface area SPHERE has the largest volume, not CUBE..

+1 vote

Let's take $100$ units as the perimeter

Circle:

• $2πr = 100$
• $\implies r = 100/(2π) = 100/(2\times 3.14) = 15.92$ units
• Area $= πr^2$
• $=3.14\times 15.92\times 15.92 = 795.82$ square units

Square:

• $4a = 100$
• $\implies a = 25$units
• Area $= a\times a = 25\times 25 = 625$ square units

Equilateral Triangle:

• $3s = 100$
• $s = 100/3 = 33.33$ units
• Area $=\frac{\sqrt 3 }{ 4} s^2$
• $=\frac{\sqrt 3}{4} \times 33.33 \times 33.33$
• $= 481.029$ square units

$795.82 > 625 > 481.029$

Circle Area > Square Area > Equilateral Triangle Area

Hence, A is Correct.

by Active (4.9k points)
edited by
0
It is correct- but for a given perimeter circle has the largest area - it is in the definition of circle.
Answer:

0 votes
2 answers
2
0 votes
1 answer
4


text:
# Initial value formulation (general relativity)

Initial value formulation (general relativity)

The initial value formulation is a way of expressing the formalism of Einstein's theory of general relativity in a way that describes a universe evolving over time.

Each solution of Einstein's equation encompasses the whole history of a universe – it is not just some snapshot of how things are, but a whole spacetime: a statement encompassing the state of matter and geometry everywhere and at every moment in that particular universe. By this token, Einstein's theory appears to be different from most other physical theories, which specify evolution equations for physical systems; if the system is in a given state at some given moment, the laws of physics allow you to extrapolate its past or future. For Einstein's equations, there appear to be subtle differences compared with other fields: they are self-interacting (that is, non-linear even in the absence of other fields; they are diffeomorphism invariant, so two obtain a unique solution, a fixed background metric and gauge conditions need to be introduced; finally, the metric determines the spacetime structure, and thus the domain of dependence for any set of initial data, so the region on which a specific solution will be defined is not, a priori, defined. [Cf. Harvnb|Hawking|Ellis|1973|loc=sec. 7.1.]

There is, however, a way to re-formulate Einstein's equations that overcomes these problems. First of all, there are ways of re-writing spacetime as the evolution of "space" in time; an earlier version of this is due to Paul Dirac, while a simpler way is known after its inventors Arnowitt, Deser and Misner as ADM formalism. In these formulations, also known as "3+1" approaches, spacetime is split into a three-dimensional hypersurface with interior metric and an embedding into spacetime with exterior curvature; these two quantities are the dynamical variables in a Hamiltonian formulation tracing the hypersurface's evolution over time. [Harvnb|Arnowitt|Deser|Misner|1962; for a pedagogical introduction, see Harvnb|Misner|Thorne|Wheeler|1973|loc=§21.4–§21.7.] With such a split, it is possible to state the initial value formulation of general relativity. It involves initial data which cannot be specified arbitrarily but needs to satisfy specific constraint equations, and which is defined on some suitably smooth three-manifold $Sigma$; just as for other differential equations, it is then possible to prove existence and uniqueness theorems, namely that there exists a unique spacetime which is a solution of Einstein equations, which is globally hyperbolic, for which $Sigma$ is a Cauchy surface (i.e. all past events influence what happens on $Sigma$, and all future events are influenced by what happens on it), and has the specified internal metric and extrinsic curvature; all spacetimes that satisfy these conditions are related by isometries. [Harvnb|Fourès-Bruhat|1952 and Harvnb|Bruhat|1962; for a pedagogical introduction, see Harvnb|Wald|1984|loc=ch. 10; an online review can be found in Harvnb|Reula|1998.]

The initial value formulation with its 3+1 split is the basis of numerical relativity; attempts to simulate the evolution of relativistic spacetimes (notably merging black holes or gravitational collapse) using computers. [See Harvnb|Gourgoulhon|2007.] However, there are significant differences to the simulation of other physical evolution equations which make numerical relativity especially challenging, notably the fact that the dynamical objects that are evolving include space and time itself (so there is no fixed background against which to evaluate, for instance, perturbations representing gravitational waves) and the occurrence of singularities (which, when they are allowed to occur within the simulated portion of spacetime, lead to arbitrarily large numbers that would have to be represented in the computer model). [For a review of the basics of numerical relativity, including the problems alluded to here and further difficulties, see Harvnb|Lehner|2001.]

ee also

*Einstein's equations

Notes

References

*Arnowitt, Richard; Stanley Deser& Charles W. Misner(1962),"The dynamics of general relativity", inWitten, L.,"Gravitation: An Introduction to Current Research", Wiley, pp. 227-265
*Bruhat, Yvonne(1962),"The Cauchy Problem", inWitten, Louis,"Gravitation: An Introduction to Current Research", Wiley, pp. 130
*Citation
first=Yvonne
last= Fourès-Bruhat
title= Théoréme d'existence pour certains systémes d'équations aux derivées partielles non linéaires
journal= Acta Mathematica
volume=88
year=1952
pages=141–225

*Citation
first=Eric
last=Gourgoulhon
title=3+1 Formalism and Bases of Numerical Relativity
id=arxiv|gr-qc|0703035
year=2007

*Citation
last1=Hawking
first1=Stephen W.
last2=Ellis
first2=George F. R.
title=The large scale structure of space-time
publisher=Cambridge University Press
isbn=0-521-09906-4
year=1973

*Citation
last=Lehner
first=Luis
title=Numerical Relativity: A review
journal =Class. Quant. Grav.
volume=18
year=2001
pages=R25-R86
id=arxiv|gr-qc|0106072

* Misner, Charles W.; Kip. S. Thorne& John A. Wheeler(1973),"Gravitation", W. H. Freeman, ISBN 0-7167-0344-0
*Citation
first= Oscar A.
last=Reula
title=Hyperbolic Methods for Einstein's Equations
journal=Living Rev. Relativity
volume=1
year=1998
url=http://www.livingreviews.org/lrr-1998-3
accessdate=2007-08-29

* Wald, Robert M.(1984),""General Relativity"", Chicago: University of Chicago Press, ISBN 0-226-87033-2

Wikimedia Foundation. 2010.

### Look at other dictionaries:

• General relativity — For a generally accessible and less technical introduction to the topic, see Introduction to general relativity. General relativity Introduction Mathematical formulation Resources …   Wikipedia

• Golden age of general relativity — The Golden Age of General Relativity is the period roughly from 1960 to 1975 during which the study of general relativity, which had previously been regarded as something of a curiosity, entered the mainstream of theoretical physics. During this… …   Wikipedia

• Exact solutions in general relativity — In general relativity, an exact solution is a Lorentzian manifold equipped with certain tensor fields which are taken to model states of ordinary matter, such as a fluid, or classical nongravitational fields such as the electromagnetic field.… …   Wikipedia

• Mathematics of general relativity — For a generally accessible and less technical introduction to the topic, see Introduction to mathematics of general relativity. General relativity Introduction Mathematical formulation Resources …   Wikipedia

• Contributors to general relativity — General relativity Introduction Mathematical formulation Resources Fundamental concepts …   Wikipedia

• Mass in general relativity — General relativity Introduction Mathematical formulation Resources Fundamental concepts …   Wikipedia

• Numerical relativity — is one of the branches of general relativity that uses numerical methods and algorithms to solve and analyze problems. To this end, supercomputers are often employed to study black holes, gravitational waves, neutron stars and many other… …   Wikipedia

• History of special relativity — The History of special relativity consists of many theoretical and empirical results of physicists like Hendrik Lorentz and Henri Poincaré, which culminated in the theory of special relativity proposed by Albert Einstein, and subsequent work of… …   Wikipedia

• Time value of money — The time value of money is the value of money figuring in a given amount of interest earned over a given amount of time. The time value of money is the central concept in finance theory. For example, \$100 of today s money invested for one year… …   Wikipedia

• Path integral formulation — This article is about a formulation of quantum mechanics. For integrals along a path, also known as line or contour integrals, see line integral. The path integral formulation of quantum mechanics is a description of quantum theory which… …   Wikipedia

We are using cookies for the best presentation of our site. Continuing to use this site, you agree with this.


text:
# M-Ary Signalling MCQ || M-Ary Signalling Questions and Answers

1. To increase the rate of communication by log2M in M-array communication, the power requirement increased by

1. 2M
2. M2
3. MM
4. 2M

Explanation

The distance of each signaling point from the origin is given by √Es

Where Es = Eblog2M.

Power in M-array communication is given by Es

As Es = Eblog2M

To increase power by log2M,

Es = Eb(log2M)2

Es = Eblog2M2

Es = 2Eblog2M

Hence to increase the rate of communication by log2M in M-array communication,

the power requirement increased by M2.

2. The limit which represents the threshold Eb/N0 value below which reliable communication cannot be maintained is called as

1. Probability limit
2. Error limit
3. Shannon limit
4. Communication limit

Explanation

The Shannon capacity theorem defines the maximum amount of information, or data capacity, which can be sent over any channel or medium (wireless, coax, twisted pair, fiber, etc.). What this says is that the higher the signal-to-noise (SNR) ratio and the more the channel bandwidth, the higher the possible data rate.

Eb/N0 curve has a waterfall shape. Shannon limit gives the threshold value below which reliable communication cannot be maintained.

3. The length of cable required for transmitting data at the rate of 500 Mbps in an Ethernet LAN with frames of size 10,000 bits and for signal speed 2,00,000 km/s is

1. 2.5 km
2. 2.0 km
3. 1.5 km
4. 1.0 km

Explanation

Bandwidth = 500 mbps

Frame size = 10,000 bits

Signal speed = 2,00,000 km/sec

Transmission delay = 2 × propagation delay

frame size/bandwidth = 2 × (length of the cable /signal speed)

Length of the cable =  (20000 × 10000)/(2 × 500 × 106)

Length of the cable =  2 Km

4. Which modulation scheme will have minimal BER?

1. QPSK
2. 8-PSK
3. 16-PSK
4. 16-QAM

Explanation

Probability of error (Pe) = $Q\sqrt {\frac{{{E_b}}}{{{N_0}}}}$

Pe is minimum when energy (Eb) is maximum.

Now,

Eb ∝ d2 (distance between the symbol)

i.e., Pe is minimum when the distance is maximum.

Analysis:

BER (Bit Error Ratio) Is a Signal Quality Quantitative Measurement of Digital Communication Systems. Out of the given scheme, QPSK has the maximum distance, and hence Pe is minimum in QPSK.  For M-ary as M increases, the distance between symbols decreases.

5. M-ary signaling produces _______ error performance with orthogonal signaling and _______ error performance with multiple phase signaling.

3. Improved, improved

Explanation

In M-ary signaling as k increases, the curve moves towards the degraded error performance. It produces improved error performance in the case of orthogonal signaling and degraded error performance in the case of multiple-phase signaling.

6. A full-duplex binary FSK transmission is made through a channel of bandwidth 10 kHz. In each direction of transmission, the two carriers used for the two states are separated by 2 kHz. The maximum baud rate for this transmission is:

1. 2000 bps
2. 3000 bps
3. 5000 bps
4. 10000 bps

Explanation

The bandwidth for a full-duplex binary FSK transmission is given by:

B.W. = Baud rate + f2 – f1

Calculation:

Because the transmission is full-duplex only 5000 (5 kHz) is allocated for each direction.

Given f2 – f1 2k – 2000

Band rate = BW – (f2 – f1) – 5000 – 2000

Band rate = 3000 bps

7. What is the relation between bandwidth B of BPSK signal and the bandwidth Bm of the M-ary PSK signal, for a given data rate?

1. Bm = MB
2. Bm = B log2 M
3. B = Bm log2 M
4. B = M⋅Bm

Answer.3. B = Bm log2 M

Explanation

M-array PSK:

For m-array PSK minimum bandwidth to pass digitally modulated carrier is given as:

$B.W. = \frac{{{R_b}}}{{{{\log }_2}M}}$ ——– 1

BPSK:

For BPSK M = 2 so,

$B = \frac{{{R_b}}}{{{{\log }_2}2}} = {R_b}$ ——- 2

From Equation 1 and 2;

B = Bm log2 M

8. Which M-ary is more vulnerable to noise?

1. 4-ary system
2. 2-ary system
3. Binary system
4. None of the mentioned

Explanation

An M-ary transmission is a type of digital modulation where instead of transmitting one bit at a time, two or more bits are transmitted simultaneously.

QPSK is a 4-ary system, that is, it has 4 different states each represented by a set of 2 binary digits, i.e., 00, 01, 10, 11. Likewise, an 8-ary system has 8 different states each represented by a set of 3 binary digits, i.e., 000, 001, ….., 111, a 16-ary system has 16 different states represented by a set of 4 binary digits, i.e., 0000, 0001, ….., 1111, and so on.

The minimum energy noise vector for 4-ary system is smaller than 2-ary system. So 4-ary system is more vulnerable to noise.

9. An M-level PSK modulation scheme is used to transmit independent binary digits over a band-pass channel with a bandwidth of 100 kHz. The bit rate is 200 kbps and the system characteristic is a raised-cosine spectrum with 100% excess bandwidth. The minimum value of M is

1. 10
2. 14
3. 16
4. 20

Explanation

For M-PSK bandwidth of signal given by B $= \frac{{{R_b} \times \left( {1 + \propto } \right)}}{{logM}}$

Given bit rate  = 200kbps, excess bandwidth = 100

⇒ 100 KHz $= \frac{{200\: \times \:{{10}^3} \times \:2}}{{logM}}$

⇒ Log M = 4

M = 16

10. Arrange the bandwidth efficiency of the following M-ary modulation schemes in descending order

(A) 8 – ary PSK

(B) 8 – ary FSK

(C) 16 – ary FSK

(D) 16 – ary PSK

(E) 4 – ary FSK

Choose the correct answer from the options given below:

(1) (D), (C), (A). (B), (E)

(2) (D), (E), (A). (C), (B)

(3) (C), (D), (B). (A), (E)

(4) (D), (A), (E). (B), (C)

1. 1
2. 2
3. 3
4. 4

Explanation

M-array PSK:

For m-array PSK minimum bandwidth to pass digitally modulated carrier is given as:

$B.W. = \frac{{{R_b}}}{{{{\log }_2}M}}$

M-array Bandwidth of FSK is given as;

$BW = \frac{{{2^{N + 1}}{R_b}}}{N}$

Where N = log2 M

Rb = Bit wave

Bandwidth efficiency = Bit wave (Rb)/Bandwidth

Calculation:-

(A) 8-array PSK:

Bandwidth $= \frac{{2{R_b}}}{{{{\log }_2}8}} = \frac{2}{3}{R_b}$

Bandwidth efficiency $= \frac{{2{R_b}}}{{\frac{2}{3}{R_b}}} = 1.5$

(B) 8-array FSK:-

N = log2 8 = 3

Bandwidth = $\begin{array}{l} = \frac{{{2^{N + 1}}{R_b}}}{N}\\ \\ = \frac{{{2^4}{R_b}}}{3} = \frac{{16}}{3}{R_b} \end{array}$

(C) 16-array FSK:-

N = log2 16 = 4

Bandwidth $= \frac{{{2^5}{R_b}}}{4} = \frac{{32}}{4}{R_b} = 8\:{R_b}$

Bandwidth efficiency $= \frac{{{R_b}}}{{8\:{R_b}}} = 0.125$

(D) 16-array PSK:-

Bandwidth $= \frac{{2{R_b}}}{{{{\log }_2}16}} = \frac{2}{4}{R_b} = \frac{{{R_b}}}{2}$

Bandwidth efficiency $= \frac{{{R_b}}}{{\frac{{{R_b}}}{2}}} = 2$

So, the decreasing order of bandwidth efficiency is:-

D > A > E > B > C

Scroll to Top


text:
# Electromagnetic Plane Waves

1. Apr 24, 2013

### Rubiss

1. The problem statement, all variables and given/known data

I'm currently trying to understand linear and circular polarization of electromagnetic plane waves. Let's say I have an electric field given by

$$\vec{E}=Acos(kx-\omega t)\hat{x}+Bcos(kx-\omega t - \gamma)\hat{y}$$

A is given and nonzero. I want to find what values of B and gamma that can make the wave linear or circularly polarized.

2. Relevant equations

I can also write the electric field as

$$\vec{E}=Re \big((A\hat{x}+Be^{-i\gamma}\hat{y})e^{i(kx-\omega t)}\big)$$

3. The attempt at a solution

For the linear polarization, I'm thinking I can either make B=0, or gamma equal to n*pi if B is not equal to zero. Can anyone comment on my thinking?

For circular polarization, I'm thinking I need to have A=B and gamma equal to n*pi/2 for odd n. I will have right handed circular polarization if n=3,7,11,... and have left handed circular polarization if n=1,5,9,... Is this thinking correct?

Is there an easier way to do this that I am not seeing?

2. Apr 26, 2013

### rude man

Are you sure it's not cos(kz - wt) etc.? Because if not this is not a possible e-m wave.

3. Apr 26, 2013

### rude man

Assuming propagation in the z direction, you can solve this by writing the E field at z = 0, writing the x and y components of E and eliminating t between them. The result is y(x,phi,A,B) which then makes it obvious the restrictions on B and phi you must impose to effect linear or circular polarization. You could even go further and do the same for elliptical polarization for extra credit ...

4. Apr 26, 2013

### rude man

OK. I never did respond to you directly. Here goes:
Right.
Almost right. B can be + or -A. The choice of sign determines right or left circular polarization. That makes it tantamount to choosing n for γ the way you did.
Hard to say since you didn't tell us how you got your results in the first place ...


text:
# Leyendo Stacktraces

Ha ocurrido un error inesperado.

Cuando el código de su robot encuentra un error inesperado, verá este mensaje aparecer en alguna salida de la consola (Driver Station o RioLog). Probablemente también notará que su robot se detiene abruptamente, o posiblemente nunca se mueva. Estos errores inesperados se denominan unhandled exceptions.

Cuando se produce una excepción no controlada, significa que su código tiene uno o más errores que deben corregirse.

Este artículo explorará algunas de las herramientas y técnicas involucradas en encontrar y corregir esos errores.

## ¿Qué es un «Stack Trace»?

El mensaje unexpected error has occurred es una señal de que se ha impreso un stack trace.

En Java y C ++, una estructura de datos stack se utiliza para almacenar información sobre qué función o método se está ejecutando actualmente.

Un stack trace imprime información acerca de lo que estaba sucediendo en el programa cuando la excepción sin manejar ocurrió. Esto apunto a las lineas de código que estaban ejecutándose justo antes de que el problema pasara. Mientras que no siempre apunta a los puntos exactos que son la causa principal de su problema, normalmente es el mejor lugar para empezar a buscar.

## ¿Qué es una «Unhandled Exception»?

Un error irrecuperable es cualquier condición que se manifieste donde el procesador no puede continuar ejecutando código. Casi siempre implica que, a pesar de que el código haya sido compilado y se está ejecutando, no hace sentido que la ejecución continúe.

En casi todos los casos, la raíz de la excepción no manejada es que el código no está correctamente implementado. Casi nunca implica que cualquier parte del hardware no esté funcionando.

## ¿Cómo resuelvo mi problema?

### Leyendo el Stack Trace

Para empezar, busque arriba de unexpected error has occurred para el stack trace.

En Java, debería verse como algo así:

Error at frc.robot.Robot.robotInit(Robot.java:24): Unhandled exception: java.lang.NullPointerException
at frc.robot.Robot.robotInit(Robot.java:24)
at edu.wpi.first.wpilibj.TimedRobot.startCompetition(TimedRobot.java:94)
at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:335)
at edu.wpi.first.wpilibj.RobotBase.lambda$startRobot$0(RobotBase.java:387)

Hay algunas cosas importantes que entender de aquí:

• Hubo un Error

• El error se provocó por una Excepción no manejada

• La excepción fue un java.lang.NullPointerException

• El error ocurrió mientras se ejecutaba la línea 24 adentro de Robot.java

• robotInit era el nombre de el método que se estaba ejecutando cuando el error sucedió.

• robotInit es una función en el paquete de frc.robot.Robot (AKA, el código de su equipo)

• robotInit was called from a number of functions from the edu.wpi.first.wpilibj package (AKA, the WPILib libraries)

The list of indented lines starting with the word at represent the state of the stack at the time the error happened. Each line represents one method, which was called by the method right below it.

For example, If the error happened deep inside your codebase, you might see more entries on the stack:

Error at frc.robot.Robot.buggyMethod(TooManyBugs.java:1138): Unhandled exception: java.lang.NullPointerException
at frc.robot.Robot.buggyMethod(TooManyBugs.java:1138)
at frc.robot.Robot.barInit(Bar.java:21)
at frc.robot.Robot.fooInit(Foo.java:34)
at frc.robot.Robot.robotInit(Robot.java:24)
at edu.wpi.first.wpilibj.TimedRobot.startCompetition(TimedRobot.java:94)
at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:335)
at edu.wpi.first.wpilibj.RobotBase.lambda$startRobot$0(RobotBase.java:387)

In this case: robotInit called fooInit, which in turn called barInit, which in turn called buggyMethod. Then, during the execution of buggyMethod, the NullPointerException occurred.

### Perform Code Analysis

Once you’ve found the stack trace, and found the lines of code which are triggering the unhandled exception, you can start the process of determining root cause.

Often, just looking in (or near) the problematic location in code will be fruitful. You may notice things you forgot, or lines which don’t match an example you’re referencing.

Nota

Developers who have lots of experience working with code will often have more luck looking at code than newer folks. That’s ok, don’t be discouraged! The experience will come with time.

A key strategy for analyzing code is to ask the following questions:

• When was the last time the code «worked» (IE, didn’t have this particular error)?

• What has changed in the code between the last working version, and now?

Frequent testing and careful code changes help make this particular strategy more effective.

### Run the Single Step Debugger

Sometimes, just looking at code isn’t enough to spot the issue. The single-step debugger is a great option in this case - it allows you to inspect the series of events leading up to the unhandled exception.

Google is a phenomenal resource for understanding the root cause of errors. Searches involving the programming language and the name of the exception will often yield good results on more explanations for what the error means, how it comes about, and potential fixes.

### Seeking Outside Help

If all else fails, you can seek out advice and help from others (both in-person and online). When working with folks who aren’t familiar with your codebase, it’s very important to provide the following information:

• The full text of the error, including the full stack trace.

## Common Examples & Patterns

There are a number of common issues which result in runtime exceptions.

### Null Pointers and References

Both C++ and Java have the concept of «null» - they use it to indicate something which has not yet been initialized, and does not refer to anything meaningful.

Manipulating a «null» reference will produce a runtime error.

For example, consider the following code:

19  PWMSparkMax armMotorCtrl;
20
21  @Override
22  public void robotInit() {
23      armMotorCtrl.setInverted(true);
24  }

When run, you’ll see output that looks like this:

********** Robot program starting **********
Error at frc.robot.Robot.robotInit(Robot.java:23): Unhandled exception: java.lang.NullPointerException
at frc.robot.Robot.robotInit(Robot.java:23)
at edu.wpi.first.wpilibj.TimedRobot.startCompetition(TimedRobot.java:107)
at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:373)
at edu.wpi.first.wpilibj.RobotBase.startRobot(RobotBase.java:463)
at frc.robot.Main.main(Main.java:23)

Warning at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:388): The robot program quit unexpectedly. This is usually due to a code error.
The above stacktrace can help determine where the error occurred.
Error at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:395): The startCompetition() method (or methods called by it) should have handled the exception above.

Reading the stack trace, you can see that the issue happened inside of the robotInit() function, on line 23, and the exception involved «Null Pointer».

By going to line 23, you can see there is only one thing which could be null - armMotorCtrl. Looking further up, you can see that the armMotorCtrl object is declared, but never instantiated.

Alternatively, you can step through lines of code with the single step debugger, and stop when you hit line 23. Inspecting the armMotorCtrl object at that point would show that it is null.

#### Fixing Null Object Issues

Generally, you will want to ensure each reference has been initialized before using it. In this case, there is a missing line of code to instantiate the armMotorCtrl before calling the setInverted() method.

A functional implementation could look like this:

19  PWMSparkMax armMotorCtrl;
20
21  @Override
22  public void robotInit() {
23      armMotorCtrl = new PWMSparkMax(0);
24      armMotorCtrl.setInverted(true);
25  }

### Divide by Zero

It is not generally possible to divide an integer by zero, and expect reasonable results. Most processors (including the roboRIO) will raise an Unhandled Exception.

For example, consider the following code:

18  int armLengthRatio;
19  int elbowToWrist_in = 39;
20  int shoulderToElbow_in = 0; //TODO
21
22  @Override
23  public void robotInit() {
24     armLengthRatio = elbowToWrist_in / shoulderToElbow_in;
25  }

When run, you’ll see output that looks like this:

********** Robot program starting **********
Error at frc.robot.Robot.robotInit(Robot.java:24): Unhandled exception: java.lang.ArithmeticException: / by zero
at frc.robot.Robot.robotInit(Robot.java:24)
at edu.wpi.first.wpilibj.TimedRobot.startCompetition(TimedRobot.java:107)
at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:373)
at edu.wpi.first.wpilibj.RobotBase.startRobot(RobotBase.java:463)
at frc.robot.Main.main(Main.java:23)

Warning at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:388): The robot program quit unexpectedly. This is usually due to a code error.
The above stacktrace can help determine where the error occurred.
Error at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:395): The startCompetition() method (or methods called by it) should have handled the exception above.

Looking at the stack trace, we can see a java.lang.ArithmeticException: / by zero exception has occurred on line 24. If you look at the two variables which are used on the right-hand side of the = operator, you might notice one of them has been initialized to zero. Looks like someone forgot to update it! Furthermore, the zero-value variable is used in the denominator of a division operation. Hence, the divide by zero error happens.

Alternatively, by running the single-step debugger and stopping on line 24, you could inspect the value of all variables to discover shoulderToElbow_in has a value of 0.

#### Fixing Divide By Zero Issues

Divide By Zero issues can be fixed in a number of ways. It’s important to start by thinking about what a zero in the denominator of your calculation _means_. Is it plausible? Why did it happen in the particular case you saw?

Sometimes, you just need to use a different number other than 0.

A functional implementation could look like this:

18  int armLengthRatio;
19  int elbowToWrist_in = 39;
20  int shoulderToElbow_in = 3;
21
22  @Override
23  public void robotInit() {
24
25     armLengthRatio = elbowToWrist_in / shoulderToElbow_in;
26
27  }

Alternatively, if zero is a valid value, adding if/else statements around the calculation can help you define alternate behavior to avoid making the processor perform a division by zero.

Finally, changing variable types to be float or double can help you get around the issue - floating-point numbers have special values like NaN to represent the results of a divide-by-zero operation. However, you may still have to handle this in code which consumes that calculation’s value.

A very common FRC-specific error occurs when the code attempts to put two hardware-related on the same HAL resource (usually, roboRIO IO pin.)

For example, consider the following code:

19  PWMSparkMax leftFrontMotor;
20  PWMSparkMax leftRearMotor;
21
22  @Override
23  public void robotInit() {
24     leftFrontMotor = new PWMSparkMax(0);
25     leftRearMotor = new PWMSparkMax(0);
26  }

When run, you’ll see output that looks like this:

********** Robot program starting **********
Error at frc.robot.Robot.robotInit(Robot.java:25): Unhandled exception: edu.wpi.first.hal.util.AllocationException: Code: -1029
PWM or DIO 0 previously allocated.
Location of the previous allocation:
at frc.robot.Robot.robotInit(Robot.java:24)
at edu.wpi.first.wpilibj.TimedRobot.startCompetition(TimedRobot.java:107)
at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:373)
at edu.wpi.first.wpilibj.RobotBase.startRobot(RobotBase.java:463)
at frc.robot.Main.main(Main.java:23)

Location of the current allocation:
at edu.wpi.first.hal.PWMJNI.initializePWMPort(Native Method)
at edu.wpi.first.wpilibj.PWM.<init>(PWM.java:66)
at edu.wpi.first.wpilibj.motorcontrol.PWMMotorController.<init>(PWMMotorController.java:27)
at edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax.<init>(PWMSparkMax.java:35)
at frc.robot.Robot.robotInit(Robot.java:25)
at edu.wpi.first.wpilibj.TimedRobot.startCompetition(TimedRobot.java:107)
at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:373)
at edu.wpi.first.wpilibj.RobotBase.startRobot(RobotBase.java:463)
at frc.robot.Main.main(Main.java:23)

Warning at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:388): The robot program quit unexpectedly. This is usually due to a code error.
The above stacktrace can help determine where the error occurred.
Error at edu.wpi.first.wpilibj.RobotBase.runRobot(RobotBase.java:395): The startCompetition() method (or methods called by it) should have handled the exception above.

This stack trace shows that a edu.wpi.first.hal.util.AllocationException has occurred. It also gives the helpful message: PWM or DIO 0 previously allocated..

Looking at our stack trace, we see two stack traces. The first stack trace shows that the first allocation occurred in Robot.java:25. The second stack trach shows that the error actually happened deep within WPILib. However, we should start by looking in our own code. Halfway through the stack trace, you can find a reference to the last line of the team’s robot code that called into WPILib: Robot.java:25.

Taking a peek at the code, we see line 24 is where the first motor controller is declared and line 25 is where the second motor controller is declared. We can also note that both motor controllers are assigned to PWM output 0. This doesn’t make logical sense, and isn’t physically possible. Therefore, WPILib purposefully generates a custom error message and exception to alert the software developers of a non-achievable hardware configuration.

#### Fixing HAL Resource Already Allocated Issues

HAL: Resource already allocated are some of the most straightforward errors to fix. Just spend a bit of time looking at the electrical wiring on the robot, and compare that to what’s in code.

In the example, the left motor controllers are plugged into PWM ports 0 and 1. Therefore, corrected code would look like this:

19  PWMSparkMax leftFrontMotor;
20  PWMSparkMax leftRearMotor;
21
22  @Override
23  public void robotInit() {
24
25     leftFrontMotor = new PWMSparkMax(0);
26     leftRearMotor = new PWMSparkMax(1);
27
28  }

gradlew is not recognized as an internal or external command is a common error that can occur when the project or directory that you are currently in does not contain a gradlew file. This usually occurs when you open the wrong directory.

In the above screenshot, you can see that the left-hand sidebar does not contain many files. At a minimum, VS Code needs a couple of files to properly build and deploy your project.

• gradlew

• build.gradle

• gradlew.bat

If you do not see any one of the above files in your project directory, then you have two possible causes.

• A corrupt or bad project.

• You are in the wrong directory.

#### Fixing gradlew is not recognized…

gradlew is not recognized... is a fairly easy problem to fix. First identify the problem source:

Are you in the wrong directory? - Verify that the project directory is the correct directory and open this.

Is your project missing essential files? - This issue is more complex to solve. The recommended solution is to recreate your project and manually copy necessary code in.