text
stringlengths 100
957k
| meta
stringclasses 1
value |
|---|---|
# Definition of relative atomic mass
I found out there are two definitions of relative atomic mass $A_\mathrm r$.
First definition is $A_\mathrm r$ is the mass of 1 atom of an element relative to 1/12 the mass of carbon-12 atom. It can be found in any chemistry school textbook.
Second definition is what I just found and dont understand. It states $A_\mathrm r$ is the mass of 1 mole of atoms relative to 1 mole of carbon-12 atoms.
Can you kindly explain second definition with examples?
$$\frac{\text{mass of one atom}}{\frac1{12}\text{ mass of one atom of }\ce{^12C}}\\=\frac{\text{mass of one atom}\times N_\mathrm{A}}{\frac1{12}\text{ mass of one atom of }\ce{^12C}\times N_\mathrm{A}}\\=\frac{\text{mass of one mole of substance}}{\frac1{12}\text{ mass of one mole of }\ce{^12C}}$$
|
{}
|
# Are there some list of the finite subgroups of the mapping class groups of low genus surfaces?
We already know the bound of the order of the finite subgroups of the $Mod(S_g)$. If we take a further step, to find all the finite subgroups, then what is the result for low genus cases? For example, are there some list of all types of the finite subgroups of $Mod(S_g)$ for $g \leq 10$?
• possible duplicate of Automorphisms of Riemann Surfaces – Ian Agol Dec 31 '13 at 19:33
• By the Nielsen realization problem (solved by Kerckhoff), any finite subgroup of the mapping class group of a compact surface is realized by a group of automorphisms of some conformal/hyperbolic/Riemann structure on the surface. Thus, your question is (essentially) a duplicate of the other question pointed out in abx's answer. en.wikipedia.org/wiki/Nielsen_realization_problem – Ian Agol Dec 31 '13 at 19:33
As pointed out in the preceding answer, what you are looking for are all possible automorphisms of a compact Riemann surface of genus $g$. You'll find some answers at this question.
• The book "Characters and Automorphism Groups of Compact Riemann Surfaces" promises GAP calculations up to $g\le 48$, but several people also say that the promised website does not exist so far. – Dietrich Burde Jan 1 '14 at 10:32
Since the maximal order of a finite subgroup of $Mod(S_g)$ is $84(g-1)$ for $g\ge 2$, and this bound is realised for infinitely many $g$'s, listing all finite subgroups might be quite hard for bigger $g$. ( Larsen proved the remarkable result that the frequency of $g$ for which the bound $84(g − 1)$ is attained is the same as the frequency of the perfect cubes in the integers.) Also, all finite groups can be realised as a subgroup of $Mod(S_g)$, for $g\ge 2$.
So it seems to me that such a list is difficult to obtain (I have not seen it), but I am not an expert, and perhaps someone knowns more here. Of course, the bound for finite cyclic subgroups is only $4g+2$, so that a list of finite cyclic subgroups seems much easier to obtain.
|
{}
|
# zbMATH — the first resource for mathematics
##### Examples
Geometry Search for the term Geometry in any field. Queries are case-independent. Funct* Wildcard queries are specified by * (e.g. functions, functorial, etc.). Otherwise the search is exact. "Topological group" Phrases (multi-words) should be set in "straight quotation marks". au: Bourbaki & ti: Algebra Search for author and title. The and-operator & is default and can be omitted. Chebyshev | Tschebyscheff The or-operator | allows to search for Chebyshev or Tschebyscheff. "Quasi* map*" py: 1989 The resulting documents have publication year 1989. so: Eur* J* Mat* Soc* cc: 14 Search for publications in a particular source with a Mathematics Subject Classification code (cc) in 14. "Partial diff* eq*" ! elliptic The not-operator ! eliminates all results containing the word elliptic. dt: b & au: Hilbert The document type is set to books; alternatively: j for journal articles, a for book articles. py: 2000-2015 cc: (94A | 11T) Number ranges are accepted. Terms can be grouped within (parentheses). la: chinese Find documents in a given language. ISO 639-1 language codes can also be used.
##### Operators
a & b logic and a | b logic or !ab logic not abc* right wildcard "ab c" phrase (ab c) parentheses
##### Fields
any anywhere an internal document identifier au author, editor ai internal author identifier ti title la language so source ab review, abstract py publication year rv reviewer cc MSC code ut uncontrolled term dt document type (j: journal article; b: book; a: book article)
The equivalence between the convergences of Ishikawa and Mann iterations for an asymptotically pseudocontractive map. (English) Zbl 1045.47057
In this paper, it is shown that the convergence of Mann iterations is equivalent to the convergence of Ishikawa iterations for asymptotically nonexpansive and asymptotically pseudocontractive mappings, using essentially the technique of {\it B. E. Rhoades} and {\it Ş. M. Şoltuz} [Int. J. Math. Math. Sci. 2003, 2645--2651 (2003; Zbl 1045.47058), see the following review]. In a similar fashion, one can show that the converence of Mann-Ishikawa iterations is equivalent to the convergence of three-step (Noor) iterations [see {\it M. Aslam Noor}, J. Math. Anal. Appl. 251, 217--229 (2000; Zbl 0964.49007)].
##### MSC:
47J25 Iterative procedures (nonlinear operator equations) 47H10 Fixed-point theorems for nonlinear operators on topological linear spaces 47H09 Mappings defined by “shrinking” properties
Full Text:
##### References:
[1] Ishikawa, S.: Fixed points by a new iteration method. Proc. amer. Math. soc. 44, 147-150 (1974) · Zbl 0286.47036 [2] Kato, T.: Nonlinear semigroup and evolution equations. J. math. Soc. Japan 19, 508-520 (1967) · Zbl 0163.38303 [3] Mann, W. R.: Mean value in iteration. Proc. amer. Math. soc. 4, 506-510 (1953) · Zbl 0050.11603 [4] Rhoades, B. E.; Şoltuz, Ş.M: On the equivalence of Mann and Ishikawa iteration methods. Internat. J. Math. math. Sci. 33, 451-459 (2003) · Zbl 1014.47052 [5] Schu, J.: Iterative construction of fixed points of asymptotically nonexpansive mappings. J. math. Anal. appl. 158, 407-413 (1991) · Zbl 0734.47036 [6] Weng, X.: Fixed point iteration for local strictly pseudocontractive mapping. Proc. amer. Math. soc. 113, 727-731 (1991) · Zbl 0734.47042
|
{}
|
INTRODUCING 5 - days-a-week problem solving session for Math Olympiad and ISI Entrance. Learn More
# Sum of Sides of Triangle | PRMO-2018 | Problem No-17
Try this beautiful Problem on Sum of Sides of Triangle from Triangle from Prmo-2018, Problem 17.
## Sum of Sides of Triangle - PRMO, 2018- Problem 17
Triangles $\mathrm{ABC}$ and $\mathrm{DEF}$ are such that $\angle \mathrm{A}=\angle \mathrm{D}, \mathrm{AB}=\mathrm{DE}=17, \mathrm{BC}=\mathrm{EF}=10$ and $\mathrm{AC}-\mathrm{DF}=12$
What is $\mathrm{AC}+$ DF ?
,
• $28$
• $30$
• $21$
• $26$
• $26$
Geometry
Triangle
## Suggested Book | Source | Answer
Pre College Mathematics
#### Source of the problem
Prmo-2018, Problem-17
#### Check the answer here, but try the problem first
$30$
## Try with Hints
#### First Hint
In $\triangle ABC$ & $\triangle DEF$, given that $\angle A$=$\angle D$ & $AB=DE$=$17$ . $BC = EF = 10$ and $AC – DF = 12.$ we have to find out $AC+DF$.
According to the question Let us assume that the point A coincides with D, B coincides with E. Now if we draw a circle with radius 10 and E(B) as center ....
Can you finish the problem?
#### Second Hint
Let M be the foot of perpendicular from B(E) to CF. So BM = 8. Hence $\mathrm{AM}=\sqrt{17^{2}-8^{2}}=\sqrt{(25)(9)}=15$
#### Third Hint
Hence $AF = 15 – 6 = 9$ & $AC = 15 + 6 = 21$
So $AC + DF = 30$
## Subscribe to Cheenta at Youtube
### 2 comments on “Sum of Sides of Triangle | PRMO-2018 | Problem No-17”
1. Rajvardhan singh Sisodiya says:
We can directly apply Cosine law
1. KOUSHIK SOM says:
yes we can..
This site uses Akismet to reduce spam. Learn how your comment data is processed.
### Cheenta. Passion for Mathematics
Advanced Mathematical Science. Taught by olympians, researchers and true masters of the subject.
HALL OF FAMESUPER STARSBOSE OLYMPIADBLOG
CAREERTEAM
support@cheenta.com
|
{}
|
# 1.What will be the unit digit of the squares of the following numbers? (i) 81 (ii) 272 (iii) 799 (iv) 3853 (v) 1234 (vi) 20387 (vii) 52698 (viii) 99880 (ix) 12796 (x) 55555
As we know that unit's place is affected only by the unit’s place of the number of which square is seen. So we have: (i) Unit digit of $$81^2$$ = 1 [Unit’s place=1 i.e, $$1 \times 1$$ =1]
(ii) Unit digit of $$272^2$$ = 4 [Unit’s place=2 i.e, $$2 \times 2$$ =4]
(iii) Unit digit of $$799^2$$ = 1 [Unit’s place=1 i.e, $$9 \times 9$$ =1]
(iv) Unit digit of $$3853^2$$ = 9 [Unit’s place=3 i.e, $$3 \times 3$$ =9]
(v) Unit digit of $$1234^2$$ = 6 [Unit’s place=4 i.e, $$4 \times 4$$ =6]
(vi) Unit digit of $$26387^2$$ = 9 [Unit’s place=7 i.e, $$7 \times 7$$ =9]
(vii) Unit digit of $$52698^2$$= 4 [Unit’s place=8 i.e, $$8 \times 8$$ =4]
(viii) Unit digit of $$99880^2$$ = 0 [Unit’s place=0 i.e, $$0 \times 0$$ =0]
(ix) Unit digit of $$12796^2$$ = 6 [Unit’s place=6 i.e, $$6 \times 6$$ =6]
(x) Unit digit of $$55555^2$$ = 5 [Unit’s place=5 i.e, $$5 \times 5$$ =5]
|
{}
|
Practical Considerations of a Butterworth Filter
I'm trying to design/implement a low-pass filter for the amateur 2M band (144-148 MHz). To meet FCC regs, I need harmonics to be at least 40dB down, so I calculated a 7-stage Butterworth Filter with a 175MHz cutoff. This gave me the following component values:
• L1, L3 = 56.70371 nH
• L2 = 90.94568 nH
• C1, C4 = 8.094927 pF
• C2, C3 = 32.77569 pF
There seems to be a lot of information on the theory of operation of these filters both on here and on other sites, but I can't find as much on the practical implementation and component selection aspects. Given that, obviously, you can't buy components with those values, I'm picking "close" values, but I'm not sure to what extent that will affect the resulting filter. I now have:
• L1, L3 = 56 nH
• L2 = 91 nH
• C1, C4 = 8 pF
• C2, C3 = 33 pF
Is there any way I can calculate/simulate what the curve for this filter will look like? Mostly I just need to calculate it at 144-148 MHz, and 288-296 MHz (the 2nd order harmonic) to make sure I'm not attenuating my pass band and that I am attenuating the harmonics adequately.
Secondly, how can I determine the voltage and current ratings I need for the components? The transmitter is a mere 1W, which should be about 10V peak, and 200mA (50 ohm characteristic impedance) but I'm not sure if that holds true of the individual components in the filter.
Finally, is there anything else I need to know in actually implementing one of these? Specific types of capacitors to use or avoid (currently planning on SMD ceramics) and the same for the inductors?
Here is a calculator that you can use and it plots frequency/phase responses AND it seems you can tweak the values: -
Here is another one.
Here is another
And another
I can't underwrite any of them but there appear to be plenty to choose from OR get LTSpice (now that's my main recommendation).
1 - Get yourself a SPICE program. Even a limited-functionality version will be able to handle this sort of thing. You'll be able to enter the exact values.
2 - That said, don't bother. Your nominal values are as good as any. At the frequencies you're working, nothing will behave exactly as you think it will. Parasitics and construction techniques will be major modifiers of your filter response.
• That's unfortunate -- so how can I build a filter if I don't know how it will behave? Apr 15 '15 at 4:37
• LTSpice is free along with the natural learning curve but it will give you what you want. Apr 15 '15 at 7:37
• @David - You start with your nominal values. Then you start modifying, testing, modifying, etc. You'll want a variable RF generator and a power meter, to start with. Once you've got a circuit that seems right, package it in the box you're going to use for final use, and test again. Apr 15 '15 at 11:20
• @WhatRoughBeast - is there a range of components I should buy to try this? Seems like a real pain to have to keep reworking a board for "trial and error". I guess I'll also need to get a variable RF generator... Apr 15 '15 at 14:55
Consider simpler alternatives to butterworth. These are relatively narrow band signals, so the harmonics also have closely defined frequencies.
Form a lowpass filter with two notches at 2nd and 3rd harmonics - these can be combined in a Cauer (elliptic) filter of lower order - less complex, easier to build.
Or given a suitable power stage, it may be possible to eliminate the 2nd harmonic by design leaving only odd order (primarily 3rd) harmonics to worry about. Then a single notch at 432 MHz as part of a 3rd order Cauer filter will suffice. (At lower frequencies, a push-pull amplifier cancels out the even harmonics, I don't know if a similar approach works at 2m.)
• Wouldn't the notches on the Cauer filter require more precision in the components, not less? Also, I can't do anything about the design of the power stage, I'm using a commercial radio module whose 2nd order harmonics are only ~4dB down on the fundamental. Apr 15 '15 at 14:57
• Unless you're building quantities of these, you may end up tuning the filters anyway ( and a notch is fairly easy to tune). Simpler structure may still win even if it requires more precision. Apr 15 '15 at 15:03
I'm wondering why you picked the Butterworth configuration in the first place for such a tight requirement. Only advantage of Butterworth that I can see is the zero passband ripple. You can get very small to almost non-existent ripple with Cauer (elliptical) filters, for a simpler circuit order and maximal rolloff. One other zero passband ripple filter topology is Chebyshev Type 2, possibly simpler, but I haven't played with it, yet.
To answer your question as to the topology and implementation of the circuit of the components you've calculated, and without further information as to your source of calculations, the components could possibly be placed in a ladder topology (aka Cauer topology) - the capacitors in shunt (ie parallel), alternating with the inductors in series, with $C_1$ leading, like so:
You may want to try a filter design program called Elsie, that has been written for the amateur radio community by a US radio amateur.
The free version of the program calculates a range of filter topologies up to a certain order, and is packed with a lot of nice features like a well-written tutoria-style online help, plotting of performance and schematic, 5%-value component substitution, editing of circuit schematic, Monte Carlo simulation, etc.; too many to list here.
You're also missing out on the fun of experimenting as a radio amateur (I'm presuming you are one, by your first sentence) if you're not willing to try at least throwing up the circuit into a circuit simulation programme/s (already mentioned by @Andy Aka and others) to play around with topology and component values.
For an open source modelling and simulation programme, try SciLab.
73s
• Also have a look at the Filters pages on microwaves101.com Jul 29 '15 at 12:33
@WhatRoughBeast is right, at those parameter values parasitics will be a big deal. However, if you had rather think about doing things than actually do things here is an alternative.
You will need a model for your filter (state space or transfer function), which you had to have to design it (even if you didn't realize it). You can use Python with the Controls System Library to analyze your system. I wanted to mention this technique because 10 years ago this required a pricey Matlab license so I think free is a good deal here.
There is a lot of functionality in there, you could analyze parameter sensitivity, step functions, or whatever. So many options you may never get around to actually trying it(don't do this). You can also do all this in Spice, but the learning curve and design iteration time is steeper.
Here is a bode plot of 1/(s+1) low pass filter.
from control.matlab import *
num = [1]
den = [1,1]
G = tf(num,den)
bode(G)
• How does one translate this into an actual implementation? I'm not sure what you meant by "rather think about doing things than actually do things." Your suggestion seems to require transforming component values into an equation to model the filter, and I'm not sure how to do that either. Apr 15 '15 at 15:24
• Many filter design tools provide a transfer function in terms of the component values, it is a common way to describe circuits. Sorry, the "think about things" was just a joke...It is easy to overthink things when building and testing them is faster. butterworth tf
– Matt
Apr 15 '15 at 15:33
|
{}
|
41 views
The number of min heap trees are possible with 15 elements such that every leaf node must be greater than all non-leaf nodes of the tree are
| 41 views
Heap with $15$ elements will be a complete binary tree, hence it will have $8$ leaf nodes, and we want all the leaf nodes to be greater than all the non-leaf nodes, hence we can only have largest $8$ elements in leaf nodes. If we place any other elements in leaf nodes then there will be at least one of the largest $8$ elements which we will need to adjust in a non-leaf node, hence given condition will be violated. For example, if the elements are integers from $1$ to $15$ then the elements $[8,15]$ must be present in the leaf nodes, if we place any other element (which will be definitely $<8$) in any leaf node, then one element from $[8,15]$ needs to be adjusted in a non-leaf node, and this adjusted non-leaf node will have element $>$ the element that we placed in the leaf node.
Also, we need the minimum element at the root node,hence the structure of the heap will be:
minimum
/ \
x x
/ \ / \
x x x x
/ \ / \ / \ / \
o o o o o o o o
Here denotes a leaf node, denotes a non-leaf node.
Now, for the $8$ leaf nodes, we can place the $8$ largest elements in any order, and there are $8!$ such orders …………. (i)
So, we have placed $8$ leaf nodes and the root node, now we are left with $15-8-1=6$ elements.Now, the nodes that we need to fill are represented by in the above heap. From the structure, it is very clear that $3$ of the remaining $6$ elements will be on the left side and remaining $3$ will be on the right side. So, we can select any $3$ of the remaining $6$ elements to be placed in the left sub tree, total ways to do this will be $^6C_3$. …………...(ii)
Now, for the selected three elements, we need to ensure that the parent element is smaller than both the children, i.e. in the following structure:
a
/ \
b c
we want to make sure that $a<b$ and $a<c$ to satisfy the property of min-heap, hence, $a$ must be the smallest element among the $3$ elements, and we can also interchange $b$ and $c$ if the above conditions are satisfied, because we know that the leaf nodes are already greater than all the non-leaf nodes. Hence, there are $2$ ways to fill the left part, i.e. we can keep $(b,c)$ or $(c,b)$ ………...(iii)
Similarly, there are $2$ ways to fill right part. .…….……...(iv)
Hence, total number of ways will be: $8!*^6C_3*2*2=3225600$
by (861 points)
edited
0
Incorrect logic.
8! Won't even come there.
Leaf will always contain max elements.
8! Logic is incorrect
0
Why do you think so?
We have 8 leaf node, which we can fill with $[8,15]$
o o o o o o o o
8 9 10 11 12 13 14 15
8 9 10 11 12 13 15 14
8 9 10 11 12 14 13 15
...
All 8! permutations of $[8,15]$ will be valid. Hence you have 8! ways to fill the bottommost level. So, 8! should definitely come there.
0
because, it is a min heap, and also a full binary tree at the same time.
A full binary tree which is a min heap, always have maximum elements in the last level
so the answer is not what you calculated.
0
always have maximum elements in the last level
What do you exactly what to say?
See, if we consider $[1,15]$ as the elements, then $[8,15]$ will be the maximum elements, right?
Now, we have to place these elements in the leaf nodes. So, assume the nodes as containers and maximum elements as items, now how many ways do you have to place $8$ items in $8$ containers? Of course $8!.$
Also, I didn’t get the meaning of this:
A full binary tree which is a min heap, always have maximum elements in the last level
Consider a heap with $7$ nodes, this will be a full binary tree too. If the elements are $[1,7]$, then the maximum $4$ elements will be {4,5,6,7}, but the following min heap is still valid without considering all of these elements in the leaf nodes:
1
/ \
2 5
/ \ / \
4 3 7 6
In a Min Binary Heap, the key at root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. (Reference)
1. 1 is smallest among all keys and it is present in the root.
2. For the left sub tree, $2$ is minimum among {2,4,3} and it is present in the root of left sub tree.
3. For the right sub tree, $5$ is minimum among { 5,7,8} and it is present in the root of right sub tree.
Notice that $3$ is a leaf node, and $3$ not one of the $4$ largest elements in the range $[1,7]$, and $5$, which is one of the $4$ largest elements is not present in leaf node, still this is a valid min heap, according to the definition of min-heap.
We chose $8$ largest elements for this question, because it was explicitly mentioned that the elements in the leaf nodes must be greater than all non-leaf elements. I mean to say that, a full binary tree which is a mean heap will not necessarily have maximum elements in the leaf nodes. We considered this constraint, only because it was explicitly mentioned in the question. Also, we can can change the relative orderings of these elements, hence we will have 8! permutations in which these elements can occur in the 8 leaf nodes.
0
Why are you considering min heap of 7 elements in the first place
The answer is min heap of 15 elements.
No matter how u draw the tree.
Leaf will always have max elements
Otherwise
Answer should be 2! * 4! * 8! As per your logic which is illogical
0
I considered $7$ element heap only to show that a full binary tree which is a mean heap will not necessarily have maximum elements in the leaf nodes.
0
And, how did $2!*4!$ come in my logic?
Do you agree with this part in the answer?
$^6C_3∗2∗2$
0
No.
You are not getting a simple point.
Leaf will always contain maximum.
Suppose you have to make a min heap with 7 nodes.
With 7 nodes maximum elements will be in leaf.
So answer is straightway 6C3 *2*2 for 7 nodes.
But you are without any reason taking internal nodes and calculating minheaps on it. And multiplying it with number of leaf factorial.
I am sure you are still not getting why my point is right.
0
How can you say this. Show me an example where you have 7 nodes and all maximum elements are not in leaf. Show me
0
Actually yes, I am not getting your point again. 😅
For an example where you have 7 nodes and all maximum elements are not in leaf, see the 7 node heap that I made in the above comment. where is not in leaf node but is.
0
Anyways, what is the correct answer according to you then?
0
|
{}
|
How to Do Convolution a 2D Signal (Image) and Result of Convolution of Two 1D Filters?
Assume a 2-D signal (i.e., some image). Load image and assume it to be signal x. Next assume that instead of having a 2-D filter you have two one D filters
$$f_1[n] =\begin{bmatrix}0.25 && 0.5 && 0.25\end{bmatrix}$$ and $$f_2[n]=\begin{bmatrix}0.25 \\ 0.5 \\ 0.25\end{bmatrix}$$ Assume that the convolution
$$f_1[n]* f_2[n] = f_3[n]= \begin{bmatrix}0.0625 && 0.125 && 0.0625\\ 0.125 && 0.25 && 0.125\\0.0625 && 0.125 && 0.0625\end{bmatrix}$$
Using this information and output at each stage verify that Associative property holds.
My code:
f3 = [0.0625 0.125 0.0625; 0.125 0.25 0.125; 0.0625 0.125 0.0625]
conv2('x, f3)
But this gives error saying x is not a vector. How do I fix this?
• It would be nice if you could edit your post with a more readable typesetting of the matrices, etc. – Laurent Duval Apr 1 '17 at 18:45
• Did what Laurent asked for, Maya, because I agree with him! You just have to use single or double \$ around your TeX formulas instead of **! – Marcus Müller Apr 2 '17 at 8:06
• @MarcusMüller I didn't know that! – Maya Apr 2 '17 at 10:34
• @Maya that's why I'm telling you ;) Have a great day! – Marcus Müller Apr 2 '17 at 10:41
You should show that conv2(f3,x) can be implemented in a separable way. In other words, computing x1 = conv2(f1,x), then applying f2 on the results, x12 = conv2(f2,x1) gives the same result. Or f12 = conv2(f2,f1) then x12 = conv2(f12,x).
You should be aware of the correct "dimensions" for f1 and f2: transpose of each other, so that one works on "rows" and the other on columns.
This is shown in the following Matlab code:
dataImage = zeros(25,25);
% Create a delta-like image
dataImage(13,13)=1;
% Create a random-kernel image
dataImage(11:13,11:13)=rand(3,3);
imagesc(dataImage);colormap gray
f1 = [0.25 0.5 0.25]'; f2 = [0.25 0.5 0.25];
disp(f1*f2);
f3 = [0.0625 0.125 0.0625; 0.125 0.25 0.125; 0.0625 0.125 0.0625];
disp(f3);
dataImagef1f2 = conv2(f2,conv2(f1,dataImage));
dataImagef1f2 = conv2(conv2(f2,f1),dataImage);
dataImagef3 = conv2(f3,dataImage);
subplot(2,2,1)
imagesc(dataImage);
xlabel('data')
subplot(2,2,2)
imagesc(dataImagef1f2);
xlabel('(data*f1)*f2')
subplot(2,2,3)
imagesc(dataImagef1f2);
xlabel('(f1*f2)*data')
subplot(2,2,4)
imagesc(dataImagef3);
xlabel('f3')
Suggestions for tutorials:
• Can you tell me whay did you create kernel and delta like images? And why does it have to be grayscale image? I am new to image processing/ – Maya Apr 1 '17 at 18:35
• For the demo mostly, and to avoid side effects on the borders of the images. Having enough zeros around avoid some practical issues. Plus, the linearity of convolution entails that if you prove the associativity for the dirac image, then the result extends to other images. And it would work for color images, for instance by working on different color places. This is more a Matlab-type question – Laurent Duval Apr 1 '17 at 18:42
• Can you suggest me a good resource to study image processing in matlab? – Maya Apr 1 '17 at 22:07
• I am studying this course 'signals and systems" in university and have just begun using matlab but I cannot find detailed tutorial about image processing in thus course book : Attaway's Introduction to Matlab – Maya Apr 5 '17 at 18:40
• I don't have enough rep to upvote, sorry :/ – Maya Apr 5 '17 at 19:08
|
{}
|
Detection and Forecast of Climate Change Signal over the Korean Peninsula
Title & Authors
Detection and Forecast of Climate Change Signal over the Korean Peninsula
Sohn, Keon-Tae; Lee, Eun-Hye; Lee, Jeong-Hyeong;
Abstract
The objectives of this study are the detection and forecast of climate change signal in the annual mean of surface temperature data, which are generated by MRI/JMA CGCM over the Korean Peninsula. MRI/JMA CGCM outputs consist of control run data(experiment with no change of $\small{CO_2}$ concentration) and scenario run data($\small{CO_2}$ 1%/year increase experiment to quadrupling) during 142 years for surface temperature and precipitation. And ECMWF reanalysis data during 43 years are used as observations. All data have the same spatial structure which consists of 42 grid points. Two statistical models, the Bayesian fingerprint method and the regression model with autoregressive error(AUTOREG model), are separately applied to detect the climate change signal. The forecasts up to 2100 are generated by the estimated AUTOREG model only for detected grid points.
Keywords
Climate change;temperature;MRI/JMA CGCM;AUTOREG model;Bayesian fingerprint method;
Language
Korean
Cited by
References
1.
국가과학기술자문회의 (2007). <기후변화의 현황과 전망>
2.
국립기상연구소 기후연구실 (2004). <한반도 기후 100년 변화와 미래 전망>
3.
Berliner, L. M., Levine, R. A. and Shea, D. J. (2000). Bayesian climate change assessment, Journal of Climate, 13, 3805-3820
4.
Brohan, P., Kennedy, J. J., Harris, I., Tett, S. F. B. and Jones, P. D. (2006). Uncertainty estimates in regional and global observed temperature changes: A new data set from 1850, Journal of Geophysical Research, 111, D12106
5.
Etheridge, D. M., Steele, L. P., Langenfelds, R. L., Francey, R. J., Barnola, J. M. and Morgan, V. I. (1996). Natural and anthropogenic changes in atmospheric \$CO_2\$ over the last 1000 years from air in Antarctic ice and firn, Journal of Geophysical Research, 101, 4115-4128
6.
Hansen, J., Ruedy, R., Sato, M., Imhoff, M., Lawrence, W., Easterling, D., Peterson, T. and Karl, T. (2001). A closer look at United States and global surface temperature change. Journal of Geophysical Research, 106, 23947-23963
7.
Indermuhle, A., Stocker, T. F., Joos, F., Fischer, H., Smith, H. J., Wahlen, M., Deck, B., Mastroianni, D., Tschumi, J., Blunier, T., Meyer, R. and Stauffer, B. (1999). Holocene carbon-cycle dynamics based on \$CO_2\$ trapped in ice at Taylor Dome, Antarctica, Nature, 398, 121-126
8.
IPCC (2001). Climate Change 2001, http://www.grida.no/climate/ipcc tar/wg1
9.
IPCC (2007). Climate Change 2007, http://www.ipcc.ch/ipccreports/ar4-wg1.htm
10.
Neftel, A., Moor, E., Oeschger, H. and Stauffer, B. (1985). Evidence from polar ice cores for the increase in atmospheric \$CO_2\$ in the past 2 centuries, Nature, 315, 45-47
11.
Smith, T. M. and Reynolds, R. W. (2004). Improved extended reconstruction of SST (1854-1997), Journal of Climate, 17, 2466-2477
|
{}
|
Learn Quant Online
Using our exercises, videos, blogs and many more features, you can now learn quantitative aptitude online through JustQuant.com. Register now and start learning.
Talk to Our Team
As you learn, you can interact with the people behind Justquant.com. Your suggestions and feedback will be valued the most to make JustQuant.com a better place for learning quantitative aptitude
Communicate with People
We at Justquant.com are working on features to help you communicate not just with our team but also with the other members enabling you to learn quantitative aptitude better.
5,000 1,000
Divisibility Rules
Given a number $x$, can you determine if it is divisible by a number say $y$ with out even performing the actual division. Divisibility rules are quite handy when you want to test for divisibility of numbers even before you can actual divide the number. For instance, to check if a number is divisible by 7, […]
Problems on Divisors of Number
In this post we will have a look at the problems on the number of divisors of a number. We will see how to find the number of divisors of a number, number of even and odd divisors of a number, sum of divisors of a number and product of divisors of a number. The […]
|
{}
|
¿Todavía tienes preguntas de matemáticas?
Pregunte a nuestros tutores expertos
Algebra
Pregunta
33. A class reading log shows how many chapters each student reads per week. The histogram shows the data from the class reading log. According to the histogram, which statement is true?
A There are a total of $$30$$ students in the class.
B There are a total of $$32$$ students in the class.
C There are a total of $$34$$ students in the class.
D There are a total of $$46$$ students in the class.
34. Amir and Angelina both solve the equation $$3 \frac { 1 } { 4 } x = 26 .$$ The table shows Amir's and Angelina's work. Which statement is true?
A Amir solves the equation correctly because he divides both sides of the equation by $$3 \frac { 1 } { 4 }$$ and finds that $$x = 8$$ .
B Amir solves the equation correctly because he multiplies both sides of the equation by $$3 \frac { 1 } { 4 }$$ and finds that $$x = 8$$ .
C Angelina solves the equation correctly because she divides both sides of the equation by $$3 \frac { 1 } { 4 }$$ and finds that $$x = 84.5$$ .
D Angelina solves the equation correctly because she multiplies both sides of the equation by $$3 \frac { 1 } { 4 }$$ and finds that $$x = 84.5$$ .
Answer
33. B
34. A
Solución
View full explanation on CameraMath App.
|
{}
|
# Homework Help: Entropy Change in a Reversible Process multiple phase change
Tags:
1. Jul 29, 2016
### elements
1. The problem statement, all variables and given/known data
(a)How much heat must be added to a block of 0.120kg of frozen ammonia initially at 100oC to convert it to a gas at 80oC given the following information?
(b) assuming this could be done using a reversible process what would be the total entropy change associated with this operation given that ΔS=∫dQ/T (from b to a where b= Ti and a=Tf
T melt = -78 C
Tvap = -33 C
c solid = 2030
Lf = 332000
C liquid = 4750
Lv=1370000
c, gas = 28
M = 17.0 g/mol
2. Relevant equations
ΔS=∫dQ/T
3. The attempt at a solution
I've figured out the first part the heat added is simply 2.36 x 105J
But I can't seem to get the second part analyzing the integral:
$$ΔS= \int_{173.15K}^{353.15K}\frac {dQ} T \$$
where $$dQ = mcdT$$
by integrating the function I get:
$$ΔS =0.120kg * 4750J/kgK *( ln(353.15) - ln(173.15))$$
I get ~ 400 J/K as an answer and the actual answer is 865 J/K ... I dont get what i'm doing wrong, is this the right path to take or am I actually suppose to take the integral from init Temp to melting point temp then from melting point temp to vaporization temp then to 80 oC ?
2. Jul 29, 2016
### rude man
You must compute the entropy change separately for the different stages:
1. 173K to 195K
2. heat of fusion at 195K
3. 195K to 240K
4. heat of vaporization at 240K
5. 240K to 353K
That's 3 different integrals and two "gimmes" to compute the entire change in S.
|
{}
|
# Galois theory, discriminants and torsion subgroup of elliptic curves
@article{GarcaSelfa2010GaloisTD,
title={Galois theory, discriminants and torsion subgroup of elliptic curves},
author={Irene Garc{\'i}a-Selfa and Enrique Gonz{\'a}lez-Jim{\'e}nez and Jos{\'e} M. Tornero},
journal={Journal of Pure and Applied Algebra},
year={2010},
volume={214},
pages={1340-1346}
}
• Published 10 November 2008
• Mathematics
• Journal of Pure and Applied Algebra
7 Citations
On the ubiquity of trivial torsion on elliptic curves
• Mathematics
• 2010
The purpose of this paper is to give a down-to-earth proof of the well-known fact that a randomly chosen elliptic curve over the rationals is most likely to have trivial torsion.
Arithmetic Algebraic Geometry
• Mathematics
• 2015
[3] , Visible evidence for the Birch and Swinnerton-Dyer conjecture for modular abelian varieties of analytic rank zero, Math. Finiteness results for modular curves of genus at least 2, Amer.
Torsion of rational elliptic curves over quadratic fields
• Mathematics
• 2014
Let $$E$$E be an elliptic curve defined over $${\mathbb {Q}}$$Q. We study the relationship between the torsion subgroup $$E({\mathbb {Q}})_{{{\mathrm{tors}}}}$$E(Q)tors and the torsion subgroup
## References
SHOWING 1-10 OF 49 REFERENCES
A complete diophantine characterization of the rational torsion of an elliptic curve
• Mathematics
• 2007
We give a complete characterization for the rational torsion of an elliptic curve in terms of the (non-)existence of integral solutions of a system of diophantine equations.
Computing the Rational Torsion of an Elliptic Curve Using Tate Normal Form
• Mathematics
• 2002
It is a classical result (apparently due to Tate) that all elliptic curves with a torsion point of order n(4⩽n⩽10, or n=12) lie in a one-parameter family. However, this fact does not appear to have
Simplest Cubic Number Fields
• Mathematics
• 2012
In this paper we intend to show that certain integers do not occur as the norms of principal ideals in a family of cubic fields studied by Cohn, Shanks, and Ennola. These results will simplify the
Abelian L-adic representation and elliptic curves
This classic book contains an introduction to systems of l-adic representations, a topic of great importance in number theory and algebraic geometry, as reflected by the spectacular recent
Integral Points on Elliptic Curves Defined by Simplest Cubic Fields
The complete list of integral points on elliptic curves of the form y2 = f(X) is computed and it is proved that this list is exhaustive by using the methods of Tzanakis and de Weger, together with bounds on linear forms in elliptic logarithms due to S. David.
Torsion subgroups of elliptic curves in short Weierstrass form
• Mathematics
• 2005
In a recent paper by M. Wieczorek, a claim is made regarding the possible rational torsion subgroups of elliptic curves E/Q in short Weierstrass form, subject to certain inequalities for their
The simplest cubic fields
Abstract. The cyclic cubic fields generated by x3 = ax2 + (a + 3)x + 1 are studied in detail. The regulators are relatively small and are known at once. The class numbers are al2 2 ways of the form A
Diophantine analysis and torsion on elliptic curves
In a recent paper of Bennett and the author, it was shown that the elliptic curve defined by y2 = x3 + Ax + B, where A and B are integers, has no rational points of finite order if A is sufficiently
Algorithms for Modular Elliptic Curves
This book presents a thorough treatment of many algorithms concerning the arithmetic of elliptic curves with remarks on computer implementation and an extensive set of tables giving the results of the author's implementations of the algorithms.
|
{}
|
lilypond-user
[Top][All Lists]
## Re: Aleatoric Elements with barlines
From: Aaron Hill Subject: Re: Aleatoric Elements with barlines Date: Mon, 07 Jan 2019 08:18:47 -0800 User-agent: Roundcube Webmail/1.3.8
On 2019-01-07 7:55 am, Reggie wrote:
Hi Aaron thank you for that help. I don't like to use indepedant meters
however since this section I believe should be cadenza for easy input.
However, I add spacer rests like you said but it makes everything way wrong too many repeats and breaks everything. I don't see what you mean to add. Can you give one example of a pairing of spacer and r1* to move one repeat
barline successfully? Many thanks. My error image. error.png
The article I linked covers more than just meter, specifically it covers how to have independent bar lines. You need to follow it to ensure that your bar lines do not "bleed" into the other staves.
See the following:
%%%%
\version "2.19.82"
\paper { ragged-right = ##f }
\layout {
\context { \Score
\remove "Timing_translator"
\remove "Default_bar_line_engraver"
}
\context { \Staff
\consists "Timing_translator"
\consists "Default_bar_line_engraver"
}
}
<< \new Staff \relative c'' {
r1*5/4\fermata \bar ".|:"
< d e f >1\> r1\!\fermata \bar ":|."
s1*3/4 \bar "||"
}
\new Staff \relative c'' {
r1\fermata \bar ".|:"
< d e f >1\> r1\!\fermata \bar ":|."
s1 \bar "||"
}
\new Staff \relative c'' {
r1*3/4\fermata \bar ".|:"
< d e f >1\> r1\!\fermata \bar ":|."
s1*5/4 \bar "||"
} >>
%%%%
Regarding the spacer rests (or actual rests if you wanted them to be printed), the beginning and ending rests must add up to the same total across all staves. So, for the above example, we need the rests to be equivalent to two full measures. In the first staff, scaling the leading rest by 5/4 requires a corresponding scaling of the final spacing rest to 3/4. The middle staff is trivial, and the final staff is just the opposite of the first.
-- Aaron Hill
aleatoric.cropped.png
Description: PNG image
|
{}
|
## A community for students. Sign up today
Here's the question you clicked on:
## anonymous one year ago ΔABC with vertices A(-3, 0), B(-2, 3), C(-1, 1) is rotated 180° clockwise about the origin. It is then reflected across the line y = -x. What are the coordinates of the vertices of the image?
• This Question is Open
1. LynFran
ok so |dw:1435524695372:dw|
2. LynFran
the imag of B would be (3,-2) ...did u get that?
3. LynFran
And the image of C would be (1,-1)...did u get that?
4. mathmate
hint: $$R_{180}: (x,y)->(-x,-y)$$ or premultiply by the first matix given by @lynfran $$s_{y=-x}: (x,y)->(-y,-x)$$ or premultiply by the second matrix. If you combine the two, you have $$s_{y=-x} \circ R_{180}: (x,y) -> (y,x)$$, the equivalent of $$s_{y=x}$$ or reflection about y=x. Using matrices, $\left[\begin{matrix}0 & -1 \\ -1 & 0\end{matrix}\right]\left[\begin{matrix}-1 & 0 \\ 0 & -1\end{matrix}\right]=\left[\begin{matrix}0 & 1 \\ 1 & 0\end{matrix}\right]$ Say a vertex has coordinates (2,1) The transformed coordinates would be (y,x)=(1,2) Using the combined matrix, $$\left[\begin{matrix}0 & 1\\1 & 0\end{matrix}\right]\left[\begin{matrix}2\\1 \end{matrix}\right]=\left[\begin{matrix}1\\2\end{matrix}\right]$$, or (1,2) as before.
#### Ask your own question
Sign Up
Find more explanations on OpenStudy
Privacy Policy
|
{}
|
Is the demand for table salt elastic or inelastic? Why?
a. Is the demand for table salt elastic or inelastic? Why?
b. Is the demand for stereos elastic or inelastic? Why?
|
{}
|
# Understanding MCMC Dynamics as Flows on the Wasserstein Space
It is known that the Langevin dynamics used in MCMC is the gradient flow of the KL divergence on the Wasserstein space, which helps convergence analysis and inspires recent particle-based variational inference methods (ParVIs). But no more MCMC dynamics is understood in this way. In this work, by developing novel concepts, we propose a theoretical framework that recognizes a general MCMC dynamics as the fiber-gradient Hamiltonian flow on the Wasserstein space of a fiber-Riemannian Poisson manifold. The "conservation + convergence" structure of the flow gives a clear picture on the behavior of general MCMC dynamics. We analyse existing MCMC instances under the framework. The framework also enables ParVI simulation of MCMC dynamics, which enriches the ParVI family with more efficient dynamics, and also adapts ParVI advantages to MCMCs. We develop two ParVI methods for a particular MCMC dynamics and demonstrate the benefits in experiments.
## Authors
• 89 publications
• 6 publications
• 113 publications
• ### A Divergence Bound for Hybrids of MCMC and Variational Inference and an Application to Langevin Dynamics and SGVI
Two popular classes of methods for approximate inference are Markov chai...
06/20/2017 ∙ by Justin Domke, et al. ∙ 0
• ### Accelerated First-order Methods on the Wasserstein Space for Bayesian Inference
We consider doing Bayesian inference by minimizing the KL divergence on ...
07/04/2018 ∙ by Chang Liu, et al. ∙ 0
• ### A Unified Particle-Optimization Framework for Scalable Bayesian Sampling
There has been recent interest in developing scalable Bayesian sampling ...
05/29/2018 ∙ by Changyou Chen, et al. ∙ 0
• ### Variance Reduction in Stochastic Particle-Optimization Sampling
Stochastic particle-optimization sampling (SPOS) is a recently-developed...
11/20/2018 ∙ by Jianyi Zhang, et al. ∙ 0
• ### Gromov-Wasserstein Averaging in a Riemannian Framework
We introduce a theoretical framework for performing statistical tasks—in...
10/10/2019 ∙ by Samir Chowdhury, et al. ∙ 0
• ### Ensemble Riemannian Data Assimilation over the Wasserstein Space
In this paper, we present a new ensemble data assimilation paradigm over...
09/07/2020 ∙ by Sagar K. Tamang, et al. ∙ 0
• ### Underdamped Langevin MCMC: A non-asymptotic analysis
We study the underdamped Langevin diffusion when the log of the target d...
07/12/2017 ∙ by Xiang Cheng, et al. ∙ 0
##### This week in AI
Get the week's most popular data science and artificial intelligence research sent straight to your inbox every Saturday.
## 1 Introduction
Dynamics-based Markov chain Monte Carlo (MCMC) methods in Bayesian inference have drawn great attention because of their wide applicability, efficiency in drawing samples, and scalability for large-scale datasets
(Neal et al., 2011; Welling & Teh, 2011; Chen et al., 2014, 2016; Li et al., 2019). They draw samples by simulating a continuous-time dynamics, or more precisely, a diffusion process, that keeps the target distribution invariant. However, they often exhibit slow empirical convergence and relatively small effective sample size, due to a positive sample correlation. An alternative kind of methods, called particle-based variational inference methods (ParVIs), aim to deterministically update samples, or particles as they call them, so that the particle distribution minimizes the KL divergence to the target distribution. They fully exploit the approximation ability of a set of particles by imposing an interaction among them, so they are more particle-efficient. Optimization-based principle also makes them convergence faster. Stein variational gradient descent (SVGD) (Liu & Wang, 2016) is the most famous representative, and the field is under an active development both in theory (Liu, 2017; Chen et al., 2018b, a; Liu et al., 2018) and application (Liu et al., 2017; Pu et al., 2017; Zhuo et al., 2018; Yoon et al., 2018).
The study on the relation between the two families starts from their interpretations on the 2-Wasserstein space supported on some smooth manifold (Villani, 2008; Ambrosio et al., 2008). It is defined as the space of distributions
\clP(\clM):={q∣ qis a probability measure on \clM and ∃x0∈\clM\st\bbEq(x)[d(x,x0)]<∞} (1)
with the well-known 2-Wasserstein distance. It is very general yet still has necessary structures. With its canonical metric, the gradient flow (steepest descending curves) of the KL divergence is defined. It is well-known that the Langevin dynamics (LD) (Roberts et al., 1996; Welling & Teh, 2011), a particular type of dynamics in MCMC, simulates the gradient flow on (Jordan et al., 1998). Recent analysis reveals that existing ParVIs also simulate the gradient flow (Chen et al., 2018a; Liu et al., 2018), so they simulate the same dynamics as LD. However, besides LD, there are many more types of dynamics in the MCMC field that could converge faster and produce more effective samples (Neal et al., 2011; Chen et al., 2014; Ding et al., 2014), but no ParVI yet simulates them. These more general MCMC dynamics have not been understood as a process on the Wasserstein space , and this poses an obstacle towards a ParVI simulation. On the other hand, the convergence behavior of LD becomes clear when viewing LD as the gradient flow on (Cheng & Bartlett, 2017), which leads a distribution to the target steepestly in terms of KL divergence. However, such knowledge on other MCMC dynamics remains obscure, except a few. In fact, a general MCMC dynamics is only guaranteed to keep the target distribution invariant (Ma et al., 2015), but unnecessarily drives a distribution towards the target steepestly. So it is hard for the gradient flow formulation to cover general MCMC dynamics.
In this work, we propose a theoretical framework that gives a unified view of general MCMC dynamics on the Wasserstein space . We establish the framework by two generalizations over the concept of gradient flow towards a wide coverage: (a) we introduce a novel concept called fiber-Riemannian manifold , where only the Riemannian structure on each fiber (roughly a decomposed submanifold, or a slice of ) is required, and we develop the novel notion of fiber-gradient flow on its Wasserstein space ; (b) we also endow a Poisson structure to the manifold and exploit the corresponding Hamiltonian flow on . Combining both explorations, we define a fiber-Riemannian Poisson (fRP) manifold and a fiber-gradient Hamiltonian (fGH) flow on its Wasserstein space . We then show that any regular MCMC dynamics is the fGH flow on the Wasserstein space of an fRP manifold , and there is a correspondence between the dynamics and the structure of the fRP manifold .
This unified framework gives a clear picture on the behavior of MCMC dynamics. The Hamiltonian flow conserves the KL divergence to the target distribution, while the fiber-gradient flow minimizes it on each fiber, driving each conditional distribution to meet the corresponding conditional target. The target invariant requirement is recovered in which case the fiber-gradient is zero, and moreover, we recognize that the fiber-gradient flow acts as a stabilizing force on each fiber. It enforces convergence fiber-wise, making the dynamics in each fiber robust to simulation with the noisy stochastic gradient, which is crucial for large datasets. This generalizes the discussion of Chen et al. (2014) and Betancourt (2015) on Hamiltonian Monte Carlo (HMC) (Duane et al., 1987; Neal et al., 2011; Betancourt, 2017) to general MCMCs. In our framework, different MCMCs correspond to different fiber structures thus flow components. They can be categorized into three types, each of which has its particular behavior. We make a unified study on 17 existing MCMCs under the three types.
Our framework also bridges the fields of MCMCs and ParVIs, so that on one hand, the gate to the reservoir of MCMC dynamics is opened to the ParVI family and abundant dynamics are enabled beyond LD, and on the other hand, MCMC dynamics can be now simulated in the ParVI flavor, inheriting advantages like particle-efficiency. As an example, we develop two ParVI simulation methods for stochastic gradient Hamiltonian Monte Carlo (SGHMC) (Chen et al., 2014). We demonstrate the merits of using SGHMC dynamics over LD in the ParVI field, and ParVI advantages over conventional stochastic simulation in MCMC.
Related work Ma et al. (2015) give a complete recipe on general MCMC dynamics. Their formulation guarantees the target invariant principle, but leaves the behavior of these dynamics unexplained. Recent analysis towards a broader kind of dynamics via Fokker-Planck equation (Kondratyev & Vorotnikov, 2017; Bruna et al., 2017) is still within the gradient flow formulation, thus not general enough.
On connecting MCMC and ParVI, Chen et al. (2018a) explore the correspondence between LD and Wasserstein gradient flow, and develop new implementations for dynamics simulation. However, their consideration is still confined on LD, leaving more general MCMC dynamics untouched. Gallego & Insua (2018) formulate the dynamics of SVGD as a particular kind of MCMC dynamics, but no existing MCMC dynamics is recognized as a ParVI. More recently, Taghvaei & Mehta (2018) derive an accelerated ParVI that is similar to one of our ParVI simulations of SGHMC. The derivation does not utilize the dynamics and the method connects to SGHMC only algorithmically. Our theory solidates our ParVI simulations of SGHMC, and enables extensions to much more dynamics.
## 2 Preliminaries
We first introduce the recipe for general MCMC dynamics (Ma et al., 2015), and prior knowledge on flows on a smooth manifold and its Wasserstein space .
A smooth manifold is a topological space that locally behaves like an Euclidean space. Since the recipe describes a general MCMC dynamics in an Euclidean space , it suffices to only consider that is globally diffeomorphic to , which is its global coordinate system. For brevity we use the same notation for a point on
and its coordinates due to their equivalence. A tangent vector
at can be viewed as the differentiation along the curve that is tangent to at , so can be expressed in components under basis of the tangent space at . The cotangent space at is the dual space of , and the cotangent bundle is the union . We adopt Einstein convention to omit the summation symbol for a pair of repeated indices in super- and sub-scripts (e.g. ). We assume the target distribution absolutely continuous so that we have its density function .
### 2.1 The Complete Recipe of MCMC Dynamics
The fundamental requirement on MCMCs is that the target distribution is kept stationary under the MCMC dynamics. Ma et al. (2015) give a general recipe for such a dynamics expressed as a diffusion process in an Euclidean space :
\udx=b(x)\udt+√2D(x)\udB(t),bi(x)=1p(x)∂j(p(x)(Dij(x)+Qij(x))), (2)
for any positive semi-definite matrix
(diffusion matrix) and any skew-symmetric matrix
(curl matrix), where denotes standard Brownian motion in . The term represents a deterministic drift and denotes a stochastic diffusion. It is also shown that if is positive definite, is the unique stationary distribution. Moreover, the recipe is complete, i.e., any diffusion process with stationary can be cast into this form.
The recipe gives a universal view and a unified way to analyze MCMCs. In large scale Bayesian inference tasks, the stochastic gradient (SG), a noisy estimate of
on a randomly selected data mini-batch, is crucially desired for data scalability. The dynamics is compatible with SG, since the variance of the drift is of higher order of the diffusion part
(Ma et al., 2015; Chen et al., 2015). In many MCMC instances, is taken as an augmentation of the target variable by an auxiliary variable . This could encourage the dynamics to explore a broader area to reduce sample autocorrelation and improve efficiency (e.g. Neal et al. (2011); Ding et al. (2014); Betancourt et al. (2017)).
### 2.2 Flows on a Manifold
The mathematical concept of the flow associated to a vector field on is a set of curves on , , such that the curve through any point satisfies and that its tangent vector at , , coincides with the vector . For any vector field, its flow exists at least locally (Do Carmo (1992), Sec. 0.5). We introduce two particular kinds of flows for our concern.
We consider the gradient flow on induced by a Riemannian structure (e.g. Do Carmo (1992)), which gives an inner product in each tangent space . Expressed in coordinates, , and the matrix is required to be symmetric (strictly) positive definite. The gradient of a smooth function on can then be defined as the steepest ascending direction and is expressed in coordinates as:
where is the entry of the inverse matrix of . It is a vector field and determines a gradient flow.
On , a Riemannian structure can be equipped for a Riemannian support (Otto, 2001; Villani, 2008; Ambrosio et al., 2008). The tangent space at is recognized as (Villani (2008), Thm. 13.8; Ambrosio et al. (2008), Thm. 8.3.1):
where is the set of compactly supported smooth functions on , is the Hilbert space with inner product , and the overline means closure. The tangent space inherits an inner product from , which defines a Riemannian structure on and is consistent with the Wasserstein distance (Benamou & Brenier, 2000). With this structure, the gradient of the KL divergence is given explicitly (Villani (2008), Formula 15.2, Thm. 23.18):
Noting that is a linear subspace of the Hilbert space , an orthogonal projection can be uniquely defined. For any , is the unique vector in such that (Ambrosio et al. (2008), Lem 8.4.2), where is the divergence on and when is the density w.r.t. the Lebesgue measure of the coordinate space . The projection can also be explained with a physical intuition. Let be a vector field on
, and let its flow act on the random variable
of . The transformed random variable specifies a distribution , and a distribution curve is then induced by . The tangent vector of such at is exactly .
#### 2.2.2 Hamiltonian Flows
Hamiltonian flow is an abstraction of the Hamiltonian dynamics in classical mechanics (Marsden & Ratiu, 2013). It is defined in association to a Poisson structure on a manifold (Fernandes & Marcut (2014)), which can be expressed either as a Poisson bracket , or equivalently as a bivector field via the relation . Expressed in coordinates, , where the matrix is required to be skew-symmetric and satisfy:
βil∂lβjk+βjl∂lβki+βkl∂lβij=0,∀i,j,k. (6)
The Hamiltonian vector field of a smooth function on is defined as , with coordinate expression:
Xf(x)=βij(x)∂jf(x)∂i∈Tx\clM. (7)
A Hamiltonian flow is then determined by . Its key property is that it conserves : is constant w.r.t. . The Hamiltonian flow may be more widely known on a symplectic manifold or more particularly a cotangent bundle (e.g. Da Silva (2001); Marsden & Ratiu (2013)), but these cases are not general enough for our purpose (e.g. they require to be even-dimensional).
On , a Poisson structure can be induced by the one of . Consider linear functions on in the form for . A Poisson bracket for these linear functions can be defined as (e.g. Lott (2008), Sec. 6; Gangbo et al. (2010), Sec. 7.2):
{Ff,Fh}\clP:=F{f,h}\clM. (8)
This bracket can be extended for any smooth function by its linearization at , i.e. a linear function such that . The extended bracket is then given by (Gangbo et al. (2010), Rem. 7.8), where , are the linearizations of smooth functions , at . The Hamiltonian vector field of is then identified as (Gangbo et al. (2010), Sec. 7.2):
\clXF(q)=\clXFf(q)=πq(Xf)∈Tq\clP(\clM). (9)
On the same topic, Ambrosio & Gangbo (2008) study the existence and simulation of the Hamiltonian flow on for as a symplectic Euclidean space, and verify the conservation of Hamiltonian under certain conditions. Gangbo et al. (2010) investigate the Poisson structure on the algebraic dual , a superset of , and find that the canonical Poisson structure induced by the Lie structure of coincides with Eq. (8). Their consideration is also for symplectic Euclidean , but the procedures and conclusions can be directly adapted to Riemannian Poisson manifolds. Lott (2008) considers the Poisson structure Eq. (8) on the space of smooth distributions on a Poisson manifold , and find that it is the restriction of the Poisson structure of by Gangbo et al. (2010).
## 3 Understanding MCMC Dynamics as Flows on the Wasserstein Space \clP(\clM)
This part presents our main discovery that connects MCMC dynamics and flows on the Wasserstein space . We first work on the two concepts and introduce novel concepts for preparation, then propose the unified framework and analyze existing MCMC instances under the framework.
### 3.1 Technical Development
We excavate into MCMC and Wasserstein flows and introduce novel concepts in preparation for the framework.
On the MCMC side Noting that flows on are deterministic while MCMCs involve stochastic diffusion, we first reformulate MCMC dynamics as an equivalent deterministic one for unification. Here we say two dynamics are equivalent if they produce the same distribution curve. [Equivalent deterministic MCMC dynamics] The MCMC dynamics Eq. (2) with symmetric diffusion matrix is equivalent to the deterministic dynamics in :
\udx=ϕt(x)\udt,(ϕt)i=Dij∂jlog(p/qt)+Qij∂jlogp+∂jQij, (10)
where is the distribution density of at time . Proof is provided in Appendix A.1. For any , the projected vector field can be treated as a tangent vector at , so defines a vector field on . In this way, we give a first view of an MCMC dynamics as a Wasserstein flow. An equivalent flow with a richer structure will be given in Theorem 2.
This expression also helps understanding Barbour’s generator (Barbour, 1990) of an MCMC dynamics, which can be used in Stein’s method (Stein et al., 1972) of constructing distribution metrics. For instance the standard Langevin dynamics induces the Stein’s operator, and it in turn produces a metric called the Stein discrepancy (Gorham & Mackey, 2015), which inspires SVGD, and Liu & Zhu (2017) consider the Riemannian counterparts. The Barbour’s generator maps a function to another , where obeys initial condition (Dirac measure). In terms of the linear function on , we recognize as the directional derivative of along at . This knowledge gives the expression
\clAf=1p∂j[p(Dij+Qij)(∂if)], (11)
which meets existing results (e.g. Gorham et al. (2016), Thm. 2). Details are provided in Appendix A.2.
On the Wasserstein flow side We deepen the knowledge on flows on with a Riemannian and Poisson structure of .111 We do not consider the compatibility of the Riemannian and Poisson structure so it is different from a Kähler manifold. The gradient of is given by Eq. (5), but its Hamiltonian vector field is not directly available due to its non-linearity. We first develop an explicit expression for it. [Hamiltonian vector field of KL on ] Let be the bivector field form of a Poisson structure on and endowed with the induced Poisson structure described in Section 2.2.2. Then the Hamiltonian vector field of on is
\clX\KLp(q)=πq(Xlog(q/p))=πq(βij∂jlog(q/p)∂i). (12)
Proof is provided in Appendix A.3. Note that the projection does not make much difference recalling and produce the same distribution curve through .
For a wider coverage of our framework on MCMC dynamics, we introduce a novel concept called fiber-Riemannian manifold and develop associated objects. This notion generalizes Riemannian manifold, such that the non-degenerate requirement of the Riemannian structure is relaxed. [Fiber-Riemannian manifold] We say that a manifold is a fiber-Riemannian manifold if it is a fiber bundle and there is a Riemannian structure on each fiber.
See Fig. 1 for illustration. Roughly, (of dimension ) is a fiber bundle if there are two smooth manifolds (of dimension ), (of dimension ) such that is locally equivalent to the product space (e.g. Nicolaescu (2007), Def. 2.1.21). Denoting the surjective projection as , the fiber through is defined as the submanifold , which is diffeomorphic to . The coordinate of can be decomposed with this structure: where is the coordinate of and of . Elements in have the same part. We allow or to be zero.
A fiber-Riemannian manifold furnish each fiber with a Riemannian structure that has coordinate expression . It defines a gradient on fiber with coordinate expression . Taking the union over all fibers, we define a vector field on called fiber-gradient given a function on , whose coordinate expression is , where
(\tggij(x))M×M=(0m×m0m×n0n×m((g\clMx)ij(x))n×n). (13)
Note that is tangent to the fiber and its flow moves points within each fiber. We denote the fiber-Riemannian manifold as . It is not a Riemannian manifold for since is singular.
We define a fiber bundle as the manifold that is locally equivalent to . A similar structure can be induced on it. Each of its fiber, , has a Riemannian structure induced by the one of (see Section 2.2.1), and the gradient of the function on evaluated at is the vector field on fiber (see Eq. (5)). So the fiber-gradient of on evaluated at is:
where the last equality holds since only the derivative w.r.t. survives after multiplication with and . After projection by , is a vector field on . Note that we cannot develop the fiber-gradient directly on since it is locally equivalent to thus not a fiber-Riemannian manifold.
### 3.2 The Unified Framework
We introduce a regularity assumption on MCMC dynamics that our unified framework considers. It is satisfied by almost all existing MCMCs and its relaxation will be discussed at the end of this section.
###### Assumption (Regular MCMC dynamics).
We call an MCMC dynamics regular if its corresponding matrices in formulation (2) additionally satisfies: (a) the diffusion matrix or or , where is symmetric positive definite everywhere; (b) the curl matrix satisfies Eq. (6) everywhere.
Now we formally state our unified framework, with an illustration provided in Fig. 2. [Unified framework: equivalence between regular MCMC dynamics and fGH flows on ] We call a fiber-Riemannian Poisson (fRP) manifold, and define the fiber-gradient Hamiltonian (fGH) flow on as the flow induced by the vector field
Then: (a) Any regular MCMC dynamics on targeting is equivalent to the fGF flow on for a certain fRP manifold ; (b) Conversely, for any fRP manifold , the fGF flow on is equivalent to a regular MCMC dynamics targeting in the coordinate space of ; (c) More precisely, in both cases, the coordinate expression of the fiber-Riemannian structure and Poisson structure of coincide respectively with the diffusion matrix and the curl matrix of the regular MCMC dynamics. The idea of proof is to show ( defined in Lemma 3.1) at any so that the two vector fields produce the same evolution rule of distribution. Proof details are presented in Appendix A.4.
This formulation unifies regular MCMC dynamics and flows on the Wasserstein space, and provides a direct explanation on the behavior of general MCMC dynamics. The fundamental requirement on MCMCs that the target distribution is kept stationary, turns obvious in our framework: . The Hamiltonian flow conserves (difference to ), while encourages efficient exploration in the sample space that helps faster convergence and lower autocorrelation (Betancourt et al., 2017). The fiber-gradient flow minimizes on each fiber (with ), driving to and enforcing convergence. Specification of this general behavior is discussed below.
### 3.3 Existing MCMCs under the Unified Framework
Now we make detailed analysis on existing MCMC methods under our unified framework. Depending on the diffusion matrix , they can be categorized into three types. Each type has a particular fiber structure of the corresponding fRP manifold, thus a particular behavior of the dynamics.
Type 1: is non-singular ( in Eq. (13)).
In this case, the corresponding degenerates and itself is the unique fiber, so is a Riemannian manifold with structure . The fiber-gradient flow on becomes the gradient flow on so
which indicates the convergence of the dynamics: the Hamiltonian flow conserves while the gradient flow minimizes on steepestly, so they jointly minimize monotonically, leading to the unique minimizer . This meets the conclusion in Ma et al. (2015).
The Langevin dynamics (LD) (Roberts et al., 1996), used in both full-batch (Roberts & Stramer, 2002) and stochastic gradient (SG) simulation (Welling & Teh, 2011), falls into this class. Its curl matrix makes its fGH flow comprise purely the gradient flow, allowing a rich study on its convergence (e.g. Durmus & Moulines (2016); Cheng & Bartlett (2017)). Its Riemannian version (Girolami & Calderhead, 2011) chooses as the inverse Fisher metric so that is the distribution manifold in information geometry (Amari, 2016). Patterson & Teh (2013) further explore the simulation with SG.
Type 2: ( in Eq. (13)).
In this case, and fibers degenerate. The fGF flow comprises purely the Hamiltonian flow , which conserves and helps distant exploration. We note that under this case, the decrease of is not guaranteed, so care must be taken in simulation. Particularly, this type of dynamics cannot be simulated with parallel chains unless samples initially distribute as , so they are not suitable for ParVI simulation. The lack of a stabilizing force in the dynamics also explains their vulnerability in face of SG, where the noisy perturbation is uncontrolled. This generalizes the discussion on HMC by Chen et al. (2014) and Betancourt (2015) to dynamics of this type.
The Hamiltonian dynamics (e.g. Marsden & Ratiu (2013), Chap. 2) that HMC simulates is a representative of this kind. To sample from a distribution on manifold of dimension , variable is augmented with a vector called momentum. In our framework, this is to take as the cotangent bundle , whose canonical Poisson structure corresponds to . A conditional distribution is chosen for an augmented target distribution . HMC produces more effective samples than LD with the help of the Hamiltonian flow (Betancourt et al., 2017). As we mentioned, the dynamics of HMC cannot guarantee convergence, so it relies on the ergodicity of its simulation for convergence (Livingstone et al., 2016; Betancourt, 2017). It is simulated in a deliberated way: the second-order symplectic leap-frog integrator is employed, and is successively redrew from .
HMC considers Euclidean and chooses Gaussian , while Zhang et al. (2016) take
as the monomial Gamma distribution. On Riemannian
, is chosen as , i.e. the standard Gaussian in the cotangent space (Girolami & Calderhead, 2011). Byrne & Girolami (2013) simulate the dynamics for manifolds with no global coordinates, and Lan et al. (2015) take the Lagrangian form for better simulation, which uses velocity (tangent vector) in place of momentum (covector).
Type 3: and is singular ( in Eq. (13)).
In this case, both the Hamiltonian and fiber-gradient flows take effect. The fiber-gradient flow stabilizes the dynamics only on each fiber , but this is enough for most SG-MCMCs since SG only appears on each fiber.
SGHMC (Chen et al., 2014) is the first instance of this type. Similar to the Hamiltonian dynamics, it takes and shares the same , but its is in the form in Assumption 3.2 with a constant , whose inverse defines a Riemannian structure in every fiber . Viewed in our framework, this makes the fiber bundle structure of coincides with the one of : , , and . Using Lemma 3.1, with a specified , we derive its equivalent deterministic dynamics:
⎧⎪⎨⎪⎩\udθ\udt=−∇rlogp(r|θ),\udr\udt=∇θlogp(θ)+∇θlogp(r|θ)+C∇rlogp(r|θ)q(r|θ). (17)
We note that it adds the dynamics to the Hamiltonian dynamics. This added dynamics is essentially the fiber-gradient flow on (Eq. (14)), or the gradient flow on fiber , which pushes towards . In presence of SG, the dynamics for is unaffected, but for in each fiber, a fluctuation is introduced due to the noisy estimate of , which will mislead . The fiber-gradient compensates this by guiding to the correct target, making the dynamics robust to SG.
Another famous example of this kind is the SG Nosé-Hoover thermostats (SGNHT) (Ding et al., 2014). It further augments with the thermostats to better balance the SG noise. In terms of our framework, the thermostats augments , and the fiber is the same as SGHMC.
Both SGHMC and SGNHT choose , while SG monomial Gamma thermostats (SGMGT) (Zhang et al., 2017) uses monomial Gamma, and Lu et al. (2016) choose according to a relativistic energy function to adapt the scale in each dimension. Riemannian extensions of SGHMC and SGNHT on are explored by Ma et al. (2015) and Liu et al. (2016). Viewed in our framework, they induce a Riemannian structure in each fiber .
Discussions Due to the linearity of the equivalent systems (2), (10), (15) w.r.t. , or , , MCMC dynamics can be combined. From the analysis above, SGHMC can be seen as the combination of the Hamiltonian dynamics on the cotangent bundle and the LD in each fiber (cotangent space ). As another example, Zhang et al. (2017) combine SGMGT of Type 3 with LD of Type 1, creating a Type 1 method that decreases on the entire manifold instead of each fiber. This improves the convergence, which meets their empirical observation.
Assumption 3.2(a) is satisfied by all the mentioned MCMC dynamics, and Assumption 3.2(b) is also satisfied by all except SGNHT related dynamics. On this exception, we note from the derivation of Theorem 2 that, Assumption 3.2(b) is only required for thus to be a Poisson manifold, but is not used in the deduction afterwards. Definition of a Hamiltonian vector field and its key property could also be established without the assumption, so it is possible to extend the framework under a more general mathematical concept that relaxes Assumption 3.2(b). Assumption 3.2(a) could also be hopefully relaxed by an invertible transformation from any positive semi-definite into the required form, effectively converting the dynamics into an equivalent regular one. We leave further investigations as future work.
## 4 Simulation as ParVIs
The unified framework (Theorem 2) recognizes an MCMC dynamics as an fGH flow on the Wasserstein space of an fRP manifold , expressed in Eq. (15) explicitly. Lemma 3.1 gives another equivalent dynamics that leads to the same flow on . These findings enable us to simulate these flow-based dynamics for an MCMC method, using existing finite-particle flow simulation methods in the ParVI field. This hybrid of ParVI and MCMC largely extends the ParVI family with various dynamics, and also gives advantages like particle-efficiency to MCMCs.
We select the SGHMC dynamics as an example and develop its particle-based simulations. With for a constant , and become independent, and Eq. (17) from Lemma 3.1 becomes:
⎧⎪⎨⎪⎩\udθ\udt=Σ−1r,\udr\udt=∇θlogp(θ)−CΣ−1r−C∇rlogq(r). (18)
From the other equivalent dynamics given by the framework (Theorem 2), the fGH flow (Eq. (15)) for SGHMC is:
⎧⎪⎨⎪⎩\udθ\udt=Σ−1r+∇rlogq(r),\udr\udt=∇θlogp(θ)−CΣ−1r−C∇rlogq(r)−∇θlogq(θ). (19)
The key problem in simulating these flow-based dynamics with finite particles is that the density is unknown. Liu et al. (2018) give a summary on the solutions in the ParVI field, and find that they are all based on a smoothing treatment, in a certain formulation of either smoothing density or smoothing functions. Here we adopt the Blob method (Chen et al., 2018a) that smoothes density. With a set of particles of , Blob makes the following approximation with a kernel function for :
−∇rlogq(r(i))≈−∑k∇r(i)K(i,k)r∑jK(i,j)r−∑k∇r(i)K(i,k)r∑jK(j,k)r, (20)
where . Approximation for can be established in a similar way. Note that the gradient at points outwards from , so the estimation effectively poses a repulsive interaction among particles, similar to the behavior of SVGD (Liu & Wang, 2016). The vanilla SGHMC simulates dynamics (18) with replaced by , but dynamics (19) cannot be simulated in a similar stochastic way. More discussions are provided in Appendix B.
We call the ParVI simulations of the two dynamics as pSGHMC-det (Eq. (18)) and pSGHMC-fGH (Eq. (19
)), respectively (“p” for “particle” and “det” for “deterministic”). Compared to the vanilla SGHMC, the proposed methods could converge faster and be more particle-efficient with deterministic update and explicit repulsive interaction. On the other hand, SGHMC could make a more efficient exploration and converges faster than LD, so the behavior also holds for the corresponding ParVI simulations, i.e., our methods could speed up over Blob. One may note that pSGHMC-det resembles a direct application of stochastic gradient descent with momentum (SGDM)
(Sutskever et al., 2013) to Blob, but we stress that this derivation is not theoretically sound since Blob optimizes on the infinite-dimensional manifold while SGDM is only for finite-dimensional . Moreover, the two methods can be nourished with advanced techniques in the ParVI field. This includes the HE bandwidth selection method and acceleration frameworks by Liu et al. (2018), and other approximations to like SVGD and GFSD/GFSF (Liu et al., 2018).
## 5 Experiments
Detailed settings are provided in Appendix C.
### 5.1 Synthetic Experiment
We show in Fig. 3 the equivalence of various dynamics simulations, and the advantages of pSGHMC-det and pSGHMC-fGH. We first find that all methods eventually produce properly distributed particles, demonstrating their equivalence. For ParVI methods, both proposed methods (Rows 3, 4) converge faster than Blob (Row 1), indicating the benefit of using SGHMC dynamics over LD, where the momentum accumulates in the vertical direction. For the same SGHMC dynamics, we see that our ParVI versions (Rows 3, 4) converge faster than the vanilla stochastic version (Row 2), due to the deterministic update rule. Moreover, pSGHMC-fGF (Row 4) enjoys the HE bandwidth selection method (Liu et al., 2018) for ParVIs, which makes the particles neatly and regularly aligned thus more representative for the distribution. pSGHMC-det (Row 3) does not benefit much from HE since the density on particles, , is not directly used in the dynamics (18).
### 5.2 Latent Dirichlet Allocation (LDA)
We study the advantages of our pSGHMC methods in the real-world task of posterior inference for LDA. We follow the same settings as Liu et al. (2018) and Chen et al. (2014). We see from Fig. 4(a) the saliently faster convergence over Blob, benefited from the usage of SGHMC dynamics in the ParVI field. Particle-efficiency is compared in Fig. 4(b), where we find the better results of pSGHMC methods over vanilla SGHMC under a same particle size. This demonstrates the advantage of ParVI simulation of MCMC dynamics, where particle interaction is directly considered to make full use of a set of particles.
### 5.3 Bayesian Neural Networks (BNNs)
We investigate our methods in the supervised task of training BNNs. We follow the settings of Chen et al. (2014) with slight modification explained in Appendix. Results in Fig. 5 is consistent with our claim: pSGHMC methods converge faster than Blob due to the usage of SGHMC dynamics. Their slightly better particle-efficiency can also be observed.
## 6 Conclusion
We construct a theoretical framework that connects general MCMC dynamics with flows on the Wasserstein space. By introducing novel concepts, we find that a regular MCMC dynamics corresponds to an fGH flow for an fRP manifold. The framework gives a clear picture on the behavior of various MCMC dynamics, and also enables ParVI simulation of MCMC dynamics. We group existing MCMC dynamics into 3 types under the framework and analyse their behavior, and develop two ParVI methods of SGHMC dynamics. We empirically demonstrate the faster convergence by more general MCMC dynamics for ParVIs, and particle-efficiency by ParVI simulation for MCMCs.
## Appendix
### A. Proofs
#### A.1. Proof of Lemma 3.1
Given the dynamics (2), the distribution curve is governed by the Fokker-Planck equation (e.g. Risken (1996)):
∂tqt=−∂i(qtbi)+∂i∂j(qtDij), (21)
which reduces to
∂tqt= −(∂iqt)bi−qt(∂ibi) (22) +qt(∂i∂jDij)+(∂i∂jqt)Dij (23) +(∂iqt)(∂jDij)+(∂jqt)(∂iDij) (24) = −(∂iqt)(∂jDij+∂jQij)−(∂iqt)(Dij+Qij)∂jpp (25) −qt∂i∂j(Dij+Qij)−qt(∂iDij+∂iQij)∂jpp (26) −qt(Dij+Qij)(∂i∂jpp−(∂ip)(∂jp)p2) (27) +qt(∂i∂jDij)+(∂i∂jqt)Dij (28) +(∂iqt)(∂jDij)+(∂jqt)(∂iDij) (29) = (∂iqt−qtp∂ip)(∂jDij−∂jQij) (30) −1p(∂iqt)(∂jp)(Dij+Qij) (31) −qtp(∂i∂jp)Dij+qtp2(∂ip)(∂jp)Dij+(∂i∂jqt)Dij, (32)
where we have used the symmetry of and skew-symmetry of in the last equality: and similarly ; so and similarly , .
The deterministic dynamics in the theorem with defined in Eq. (10) induces the curve
∂tqt= −∂i(qt(ϕt)i) (33) = −(∂iqt)(ϕt)i−qt(∂i(ϕt)i) (34) = −(∂iqt)Dij(∂jpp−∂jqtqt) (35) −(∂iqt)Qij(∂jpp)−(∂iqt)(∂jQij) (36) −qt(∂iDij)(∂jpp−∂jqtqt) (37) −qtDij(∂i∂jpp−(∂jp)(∂ip)p2−∂i∂jqtqt+(∂jqt)(∂iqt)q2t) (38) −qt(∂iQij)∂jpp−qtQij(∂i∂jpp−(∂jp)(∂ip)p2) (39) −qt(∂i∂jQij) (40) = (∂iqt−qtp∂ip)(∂jDij−∂jQij) (41) −1p(∂i
|
{}
|
# Arrays
Arrays
You are encouraged to solve this task according to the task description, using any language you may know.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
## 360 Assembly
* Arrays 04/09/2015
ARRAYS PROLOG
* we use TA array with 1 as origin. So TA(1) to TA(20)
* ta(i)=ta(j)
L R1,J j
BCTR R1,0 -1
SLA R1,2 r1=(j-1)*4 (*4 by shift left)
L R0,TA(R1) load r0 with ta(j)
L R1,I i
BCTR R1,0 -1
SLA R1,2 r1=(i-1)*4 (*4 by shift left)
ST R0,TA(R1) store r0 to ta(i)
EPILOG
* Array of 20 integers (32 bits) (4 bytes)
TA DS 20F
* Initialized array of 10 integers (32 bits)
TB DC 10F'0'
* Initialized array of 10 integers (32 bits)
TC DC F'1',F'2',F'3',F'4',F'5',F'6',F'7',F'8',F'9',F'10'
* Array of 10 integers (16 bits)
TD DS 10H
* Array of 10 strings of 8 characters (initialized)
TE DC 10CL8' '
* Array of 10 double precision floating point reals (64 bits)
TF DS 10D
*
I DC F'2'
J DC F'4'
YREGS
END ARRAYS
## 8051 Assembly
There are three types of fixed-length arrays:
• In the code segment - array elements are constant; good for strings, elements are easily indexed
• In internal RAM - good for small arrays; elements are easily indexed
• In external RAM - element retrieval/altering is most efficiently done sequentially, necessary for large arrays or peripherals
Dynamic (resizable) arrays are possible to implement, but are error-prone since bounds checking must be done by the programmer.
; constant array (elements are unchangeable) - the array is stored in the CODE segment
myarray db 'Array' ; db = define bytes - initializes 5 bytes with values 41, 72, 72, etc. (the ascii characters A,r,r,a,y)
myarray2 dw 'A','r','r','a','y' ; dw = define words - initializes 5 words (1 word = 2 bytes) with values 41 00 , 72 00, 72 00, etc.
; how to read index a of the array
push acc
push dph
push dpl
mov dpl,#low(myarray) ; location of array
mov dph,#high(myarray)
movc a,@a+dptr ; a = element a
mov r0, a ; r0 = element a
pop dpl
pop dph
pop acc ; a = original index again
; array stored in internal RAM (A_START is the first register of the array, A_END is the last)
; initalise array data (with 0's)
push 0
mov r0, #A_START
clear:
mov @r0, #0
inc r0
cjne r0, #A_END, clear
pop 0
; how to read index r1 of array
push psw
mov a, #A_START
add a, r1 ; a = memory location of element r1
push 0
mov r0, a
mov a, @r0 ; a = element r1
pop 0
pop psw
; how to write value of acc into index r1 of array
push psw
push 0
push acc
mov a, #A_START
mov r0, a
pop acc
mov @r0, a ; element r1 = a
pop 0
pop psw
; array stored in external RAM (A_START is the first memory location of the array, LEN is the length)
; initalise array data (with 0's)
push dph
push dpl
push acc
push 0
mov dptr, #A_START
clr a
mov r0, #LEN
clear:
movx @dptr, a
inc dptr
djnz r0, clear
pop 0
pop acc
pop dpl
pop dph
; how to read index r1 of array
push dph
push dpl
push 0
mov dptr, #A_START-1
mov r0, r1
inc r0
loop:
inc dptr
djnz r0, loop
movx a, @dptr ; a = element r1
pop 0
pop dpl
pop dph
; how to write value of acc into index r1 of array
push dph
push dpl
push 0
mov dptr, #A_START-1
mov r0, r1
inc r0
loop:
inc dptr
djnz r0, loop
movx @dptr, a ; element r1 = a
pop 0
pop dpl
pop dph
## 8th
Arrays are declared using JSON syntax, and are dynamic (but not sparse)
[ 1 , 2 ,3 ] \ an array holding three numbers
1 a:@ \ this will be '2', the element at index 1
drop
1 123 a:@ \ this will store the value '123' at index 1, so now
. \ will print [1,123,3]
[1,2,3] 45 a:push
\ gives us [1,2,3,45]
\ and empty spots are filled with null:
[1,2,3] 5 15 a:!
\ gives [1,2,3,null,15]
\ arrays don't have to be homogenous:
[1,"one", 2, "two"]
## ABAP
There are no real arrays in ABAP but a construct called internal tables.
TYPES: tty_int TYPE STANDARD TABLE OF i
WITH NON-UNIQUE DEFAULT KEY.
DATA(itab) = VALUE tty_int( ( 1 )
( 2 )
( 3 ) ).
INSERT 4 INTO TABLE itab.
APPEND 5 TO itab.
DELETE itab INDEX 1.
cl_demo_output=>display( itab ).
cl_demo_output=>display( itab[ 2 ] ).
Output:
2
3
4
5
3
## ACL2
;; Create an array and store it in array-example
(assign array-example
(compress1 'array-example
(list '(:header :dimensions (10)
:maximum-length 11))))
;; Set a[5] to 22
(assign array-example
(aset1 'array-example
(@ array-example)
5
22))
;; Get a[5]
(aref1 'array-example (@ array-example) 5)
## ActionScript
//creates an array of length 10
var array1:Array = new Array(10);
//creates an array with the values 1, 2
var array2:Array = new Array(1,2);
//arrays can also be set using array literals
var array3:Array = ["foo", "bar"];
//to resize an array, modify the length property
array2.length = 3;
//arrays can contain objects of multiple types.
array2[2] = "Hello";
//get a value from an array
trace(array2[2]);
//append a value to an array
array2.push(4);
//get and remove the last element of an array
trace(array2.pop());
procedure Array_Test is
A, B : array (1..20) of Integer;
-- Ada array indices may begin at any value, not just 0 or 1
C : array (-37..20) of integer
-- Ada arrays may be indexed by enumerated types, which are
-- discrete non-numeric types
type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
type Activities is (Work, Fish);
type Daily_Activities is array(Days) of Activities;
This_Week : Daily_Activities := (Mon..Fri => Work, Others => Fish);
-- Or any numeric type
type Fingers is range 1..4; -- exclude thumb
type Fingers_Extended_Type is array(fingers) of Boolean;
Fingers_Extended : Fingers_Extended_Type;
-- Array types may be unconstrained. The variables of the type
-- must be constrained
type Arr is array (Integer range <>) of Integer;
Uninitialized : Arr (1 .. 10);
Initialized_1 : Arr (1 .. 20) := (others => 1);
Initialized_2 : Arr := (1 .. 30 => 2);
Const : constant Arr := (1 .. 10 => 1, 11 .. 20 => 2, 21 | 22 => 3);
Centered : Arr (-50..50) := (0 => 1, Others => 0);
Result : Integer
begin
A := (others => 0); -- Assign whole array
B := (1 => 1, 2 => 1, 3 => 2, others => 0);
-- Assign whole array, different values
A (1) := -1; -- Assign individual element
A (2..4) := B (1..3); -- Assign a slice
A (3..5) := (2, 4, -1); -- Assign a constant slice
A (3..5) := A (4..6); -- It is OK to overlap slices when assigned
Fingers_Extended'First := False; -- Set first element of array
Fingers_Extended'Last := False; -- Set last element of array
end Array_Test;
Arrays are first-class objects in Ada. They can be allocated statically or dynamically as any other object. The number of elements in an array object is always constrained. Variable size arrays are provided by the standard container library. They also can be implemented as user-defined types.
## Aikido
Aikido arrays (or vectors) are dynamic and not fixed in size. They can hold a set of any defined value.
var arr1 = [1,2,3,4] // initialize with array literal
var arr2 = new [10] // empty array of 10 elements (each element has value none)
var arr3 = new int [40] // array of 40 integers
var arr4 = new Object (1,2) [10] // array of 10 instances of Object
arr1.append (5) // add to array
var b = 4 in arr1 // check for inclusion
arr1 <<= 2 // remove first 2 elements from array
var arrx = arr1[1:3] // get slice of array
var s = arr1.size() // or sizeof(arr1)
delete arr4[2] // remove an element from an array
var arr5 = arr1 + arr2 // append arrays
var arr6 = arr1 | arr2 // union
var arr7 = arr1 & arr2 // intersection
## Aime
The aime list is a heterogeneous, dynamic sequence. No special creation procedure, only declaration is needed:
list l;
Values (numbers, strings, collections, functions, etc) can be added in a type generic fashion:
l_append(l, 3);
l_append(l, "arrays");
l_append(l, pow);
The insertion position can be specified:
l_push(l, 3, .5);
l_push(l, 4, __type(l));
More aptly, values (of selected types) can be inserted in a type specific fashion:
l_p_integer(l, 5, -1024);
l_p_real(l, 6, 88);
Similarly, values can be retrieved in a type generic fashion:
l_query(l, 5);
or is type specific fashion:
l_q_real(l, 6);
l_q_text(l, 1);
## ALGOL 68
PROC array_test = VOID:
(
[1:20]INT a;
a := others; # assign whole array #
a[1] := -1; # assign individual element #
a[3:5] := (2, 4, -1); # assign a slice #
[1:3]INT slice = a[3:5]; # copy a slice #
REF []INT rslice = a[3:5]; # create a reference to a slice #
print((LWB rslice, UPB slice)); # query the bounds of the slice #
rslice := (2, 4, -1); # assign to the slice, modifying original array #
[1:3, 1:3]INT matrix; # create a two dimensional array #
REF []INT hvector = matrix[2,]; # create a reference to a row #
REF []INT vvector = matrix[,2]; # create a reference to a column #
REF [,]INT block = matrix[1:2, 1:2]; # create a reference to an area of the array #
FLEX []CHAR string := "Hello, world!"; # create an array with variable bounds #
string := "shorter" # flexible arrays automatically resize themselves on assignment #
)
Arrays in ALGOL 68 are first class objects. Slices to any portion of the array can be created and then treated equivalently to arrays, even sections of a multidimensional array; the bounds are queried at run time. References may be made to portions of an array. Flexible arrays are supported, which resize themselves on assignment, but they can't be resized without destroying the data.
## ALGOL W
begin
% declare an array %
integer array a ( 1 :: 10 );
% set the values %
for i := 1 until 10 do a( i ) := i;
% change the 3rd element %
a( 3 ) := 27;
% display the 4th element %
write( a( 4 ) ); % would show 4 %
% arrays with sizes not known at compile-time must be created in inner-blocks or procedures %
begin
integer array b ( a( 3 ) - 2 :: a( 3 ) ); % b has bounds 25 :: 27 %
for i := a( 3 ) - 2 until a( 3 ) do b( i ) := i
end
% arrays cannot be part of records and cannot be returned by procecures though they can be passed %
% as parameters to procedures %
% multi-dimension arrays are supported %
end.
## AmigaE
DEF ai[100] : ARRAY OF CHAR, -> static
da: PTR TO CHAR,
la: PTR TO CHAR
PROC main()
da := New(100)
-> or
NEW la[100]
IF da <> NIL
ai[0] := da[0] -> first is 0
ai[99] := da[99] -> last is "size"-1
Dispose(da)
ENDIF
-> using NEW, we must specify the size even when
-> "deallocating" the array
IF la <> NIL THEN END la[100]
ENDPROC
## AntLang
/ Create an immutable sequence (array)
arr: <1;2;3>
/ Get the head an tail part
t: tail[arr]
/ Get everything except the last element and the last element
nl: first[arr]
l: last[arr]
/ Get the nth element (index origin = 0)
nth:arr[n]
## APL
Arrays in APL are one dimensional matrices, defined by seperating variables with spaces. For example:
+/ 1 2 3
Is equivalent to
1 + 2 + 3
We're folding function
+
over the array
1 2 3
## App Inventor
Arrays in App Inventor are represented with Lists. Lists may be nested to any level and contain other Lists. All supported data types may be stored in a List. Basic List blocks
## Apex
Integer[] array = new Integer[10]; // optionally, append a braced list of Integers like "{1, 2, 3}"
array[0] = 42;
System.debug(array[0]); // Prints 42
Dynamic arrays can be made using Lists. Lists and array can be used interchangeably in Apex, e.g. any method that accepts a List<String> will also accept a String[]
List <Integer> aList = new List <Integer>(); // optionally add an initial size as an argument
aList.add(5);// appends to the end of the list
aList.add(1, 6);// assigns the element at index 1
System.debug(list[0]); // Prints 5, alternatively you can use list.get(0)
## AppleScript
AppleScript arrays are called lists:
set empty to {}
set ints to {1, 2, 3}
Lists can contain any objects including other lists:
set any to {1, "foo", 2.57, missing value, ints}
## Arendelle
// Creating an array as [ 23, 12, 2, 5345, 23 ]
// with name "space"
( space , 23; 12; 2; 5345; 23 )
// Getting the size of an array:
"Size of array is | @space? |"
// Appending array with 54
( space[ @space? ] , 54 )
// Something else fun about arrays in Arendelle
// for example when you have one like this:
//
// space -> [ 23, 34, 3, 6345 ]
//
// If you do this on the space:
( space[ 7 ] , 10 )
// Arendelle will make the size of array into
// 8 by appending zeros and then it will set
// index 7 to 10 and result will be:
//
// space -> [ 23, 34, 3, 6345, 0, 0, 0, 10 ]
// To remove the array you can use done keyword:
( space , done )
## Argile
Works with: Argile version 1.0.0
use std, array
(:::::::::::::::::
: Static arrays :
:::::::::::::::::)
let the array of 2 text aabbArray be Cdata{"aa";"bb"}
let raw array of real :my array: = Cdata {1.0 ; 2.0 ; 3.0} (: auto sized :)
let another_array be an array of 256 byte (: not initialised :)
let (raw array of (array of 3 real)) foobar = Cdata {
{1.0; 2.0; 0.0}
{5.0; 1.0; 3.0}
}
(: macro to get size of static arrays :)
=: <array>.length := -> nat {size of array / (size of array[0])}
printf "%lu, %lu\n" foobar.length (another_array.length) (: 2, 256 :)
(: access :)
another_array[255] = '&'
printf "`%c'\n" another_array[255]
(::::::::::::::::::
: Dynamic arrays :
::::::::::::::::::)
let DynArray = new array of 5 int
DynArray[0] = -42
DynArray = (realloc DynArray (6 * size of DynArray[0])) as (type of DynArray)
DynArray[5] = 243
prints DynArray[0] DynArray[5]
del DynArray
Works with: Argile version 1.1.0
use std, array
let x = @["foo" "bar" "123"]
print x[2]
x[2] = "abc"
## AutoHotkey
Works with: AutoHotkey_L
The current, official build of AutoHotkey is called AutoHotkey_L. In it, arrays are called Objects, and associative/index based work hand-in-hand.
myArray := Object() ; could use JSON-syntax sugar like {key: value}
myArray[1] := "foo"
myArray[2] := "bar"
MsgBox % myArray[2]
; Push a value onto the array
myArray.Insert("baz")
AutoHotkey Basic (deprecated) did not have typical arrays. However, variable names could be concatenated, simulating associative arrays. By convention, based on built-in function stringsplit, indexes are 1-based and "0" index is the length.
arrayX0 = 4 ; length
arrayX1 = first
arrayX2 = second
arrayX3 = foo
arrayX4 = bar
Loop, %arrayX0%
Msgbox % arrayX%A_Index%
source = apple bear cat dog egg fish
StringSplit arrayX, source, %A_Space%
Loop, %arrayX0%
Msgbox % arrayX%A_Index%
## AutoIt
Create an userdefined array.
#include <Array.au3> ;Include extended Array functions (_ArrayDisplay)
Local \$aInputs[1] ;Create the Array with just 1 element
While True ;Endless loop
\$aInputs[UBound(\$aInputs) - 1] = InputBox("Array", "Add one value") ;Save user input to the last element of the Array
If \$aInputs[UBound(\$aInputs) - 1] = "" Then ;If an empty string is entered, then...
ReDim \$aInputs[UBound(\$aInputs) - 1] ;...remove them from the Array and...
ExitLoop ;... exit the loop!
EndIf
ReDim \$aInputs[UBound(\$aInputs) + 1] ;Add an empty element to the Array
WEnd
_ArrayDisplay(\$aInputs) ;Display the Array
## AWK
Every array in AWK is an associative array. AWK converts each array subscript to a string, so a[33], a["33"] and a[29 + 4] are the same element.
An ordered array just uses subscripts as integers. Array subscripts can start at 1, or any other integer. The built-in split() function makes arrays that start at 1.
BEGIN {
# to make an array, assign elements to it
array[1] = "first"
array[2] = "second"
array[3] = "third"
alen = 3 # want the length? store in separate variable
# or split a string
plen = split("2 3 5 7 11 13 17 19 23 29", primes)
clen = split("Ottawa;Washington DC;Mexico City", cities, ";")
# retrieve an element
print "The 6th prime number is " primes[6]
# push an element
cities[clen += 1] = "New York"
dump("An array", array, alen)
dump("Some primes", primes, plen)
dump("A list of cities", cities, clen)
}
function dump(what, array, len, i) {
print what;
# iterate an array in order
for (i = 1; i <= len; i++) {
print " " i ": " array[i]
}
}
Output:
The 6th prime number is 13
An array
1: first
2: second
3: third
Some primes
1: 2
2: 3
3: 5
4: 7
5: 11
6: 13
7: 17
8: 19
9: 23
10: 29
A list of cities
1: Ottawa
2: Washington DC
3: Mexico City
4: New York
## Axe
1→{L₁}
2→{L₁+1}
3→{L₁+2}
4→{L₁+3}
Disp {L₁}►Dec,i
Disp {L₁+1}►Dec,i
Disp {L₁+2}►Dec,i
Disp {L₁+3}►Dec,i
## Babel
### Create an array
There are two kinds of array in Babel: value-arrays and pointer-arrays. A value-array is a flat array of data words. A pointer-array is an array of pointers to other things (including value-arrays). You can create a data-array with plain square-brackets. You can create a value-array with the [ptr ] list form:
[1 2 3]
[ptr 1 2 3]
[1 2 3] 1 th ;
Output:
[val 0x2 ]
### Change an array element
Changing a value-array element:
[1 2 3] dup 1 7 set ;
Output:
[val 0x1 0x7 0x3 ]
Changing a pointer-array element:
[ptr 1 2 3] dup 1 [ptr 7] set ;
Output:
[ptr [val 0x1 ] [val 0x7 ] [val 0x3 ] ]
### Select a range of an array
[ptr 1 2 3 4 5 6] 1 3 slice ;
Output:
[ptr [val 0x2 ] [val 0x3 ] ]
### Add a new element to an array
You can concatenate arrays of same type:
[1 2 3] [4] cat
[ptr 1 2 3] [ptr 4] cat
Concatenation creates a new array - it does not add to an array in-place. Instead, Babel provides operators and standard utilities for converting an array to a list in order to manipulate it, and then convert back.
### Convert between arrays and lists
Convert a value-array to a list of values:
[1 2 3] ar2ls lsnum !
Output:
( 1 2 3 )
Convert a list of values to a value-array:
(1 2 3) ls2lf ;
Output:
[val 0x1 0x2 0x3 ]
Convert a pointer-array to a list of pointers:
[ptr 'foo' 'bar' 'baz'] ar2ls lsstr !
Output:
( "foo" "bar" "baz" )
Convert a list of pointers to a pointer-array:
(1 2 3) bons ;
Output:
[ptr [val 0x1 ] [val 0x2 ] [val 0x3 ] ]
To learn more about manipulating arrays and lists in Babel, type "help !" (no quotes) and follow the instructions to load the man.sp file.
## BASIC
Works with: QuickBasic version 4.5
Works with: PB version 7.1
The default array base (lower bound) can be set with OPTION BASE. If OPTION BASE is not set, the base may be either 0 or 1, depending on implementation. The value given in DIM statement is the upper bound. If the base is 0, then DIM a(100) will create an array containing 101 elements.
OPTION BASE 1
DIM myArray(100) AS INTEGER
Alternatively, the lower and upper bounds can be given while defining the array:
DIM myArray(-10 TO 10) AS INTEGER
Dynamic arrays:
'Specify that the array is dynamic and not static:
'\$DYNAMIC
DIM SHARED myArray(-10 TO 10, 10 TO 30) AS STRING
REDIM SHARED myArray(20, 20) AS STRING
myArray(1,1) = "Item1"
myArray(1,2) = "Item2"
Array Initialization
Arrays are initialized to zero or zero length strings when created. BASIC does not generally have option for initializing arrays to other values, so the initializing is usually done at run time. DATA and READ statements are often used for this purpose:
DIM month\$(12)
DATA January, February, March, April, May, June, July
DATA August, September, October, November, December
FOR m=1 TO 12
NEXT m
Works with: FreeBASIC
FreeBASIC has an option to initialize array while declaring it.
Dim myArray(1 To 2, 1 To 5) As Integer => {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}}
10 REM TRANSLATION OF QBASIC STATIC VERSION
20 REM ELEMENT NUMBERS TRADITIONALLY START AT ONE
30 DIM A%(11): REM ARRAY OF ELEVEN INTEGER ELEMENTS
40 LET A%(1) = -1
50 LET A%(11) = 1
60 PRINT A%(1), A%(11)
70 END
Works with: qbasic
### Static
DIM staticArray(10) AS INTEGER
staticArray(0) = -1
staticArray(10) = 1
PRINT staticArray(0), staticArray(10)
### Dynamic
Note that BASIC dynamic arrays are not stack-based; instead, their size must be changed in the same manner as their initial declaration -- the only difference between static and dynamic arrays is the keyword used to declare them (DIM vs. REDIM). QBasic lacks the PRESERVE keyword found in some modern BASICs; resizing an array without PRESERVE zeros the values.
REDIM dynamicArray(10) AS INTEGER
dynamicArray(0) = -1
PRINT dynamicArray(0)
REDIM dynamicArray(20)
dynamicArray(20) = 1
PRINT dynamicArray(0), dynamicArray(20)
## BASIC256
# numeric array
dim numbers(10)
for t = 0 to 9
numbers[t] = t + 1
next t
# string array
dim words\$(10)
# assigning an array with a list
words\$ = {"one","two","three","four","five","six","seven","eight","nine","ten"}
gosub display
# resize arrays (always preserves values if larger)
redim numbers(11)
redim words\$(11)
numbers[10] = 11
words\$[10] = "eleven"
gosub display
end
display:
# display arrays
# using ? to get size of array
for t = 0 to numbers[?]-1
print numbers[t] + "=" + words\$[t]
next t
return
## Batch File
Arrays can be approximated, in a style similar to REXX
::arrays.cmd
@echo off
setlocal ENABLEDELAYEDEXPANSION
set array.1=1
set array.2=2
set array.3=3
set array.4=4
for /L %%i in (1,1,4) do call :showit array.%%i !array.%%i!
set c=-27
call :mkarray marry 5 6 7 8
for /L %%i in (-27,1,-24) do call :showit "marry^&%%i" !marry^&%%i!
endlocal
goto :eof
:mkarray
set %1^&%c%=%2
set /a c += 1
shift /2
if "%2" neq "" goto :mkarray
goto :eof
:showit
echo %1 = %2
goto :eof
Output:
array.1 = 1
array.2 = 2
array.3 = 3
array.4 = 4
"marry&-27" = 5
"marry&-26" = 6
"marry&-25" = 7
"marry&-24" = 8
## BBC BASIC
REM Declare arrays, dimension is maximum index:
DIM array(6), array%(6), array\$(6)
REM Entire arrays may be assigned in one statement:
array() = 0.1, 1.2, 2.3, 3.4, 4.5, 5.6, 6.7
array%() = 0, 1, 2, 3, 4, 5, 6
array\$() = "Zero", "One", "Two", "Three", "Four", "Five", "Six"
REM Or individual elements may be assigned:
array(2) = PI
array%(3) = RND
array\$(4) = "Hello world!"
REM Print out sample array elements:
PRINT array(2) TAB(16) array(3) TAB(32) array(4)
PRINT array%(2) TAB(16) array%(3) TAB(32) array%(4)
PRINT array\$(2) TAB(16) array\$(3) TAB(32) array\$(4)
## bc
There are 26 arrays available (named 'a' to 'z') with all elements initialized to zero and an installation-specific maximum size (in GNU bc you can find out the limits of your installation (BC_DIM_MAX) by invoking the limits command). Array identifiers are always followed by square brackets ('[', ']') and need not be declared/defined before usage. Indexing starts at zero.
The following is a transcript of an interactive session:
/* Put the value 42 into array g at index 3 */
g[3] = 42
/* Look at some other elements in g */
g[2]
0
g[4342]
0
/* Look at the elements of another array */
a[543]
0
/* Array names don't conflict with names of ordinary (scalar) identifiers */
g
0
g = 123
g
123
g[3]
42
## BML
Note: Variables in BML can either be placed in a prefix group(\$, @, and &) or in the world. Placing variables in the world is not recommended since it can take large sums of memory when using said variable.
% Define an array(containing the numbers 1-3) named arr in the group \$
in \$ let arr hold 1 2 3
% Replace the value at index 0 in array to "Index 0"
set \$arr index 0 to "Index 0"
% Will display "Index 0"
display \$arr index 0
% There is no automatic garbage collection
delete \$arr
## Bracmat
In Bracmat, an array is not a variable, but a stack of variables. In fact, local variables in functions are elements in arrays. Global variables are the zeroth element in such arrays. You can explicitly create an array of a specific size using the tbl function. Indexing is done by using the syntax integer\$name. Indexing is modulo the size of the array. A negative integer counts from the end of the array and backwards. The last used index is remembered by the array. Arrays can grow and shrink by calling tbl with other values. When shrinking, the values of the upper elements are lost. When growing, the current values are kept and the new elements are initialised with 0. To delete and array (and therefore the variable with the array's name), call tbl with a size 0.
( tbl\$(mytable,100)
& 5:?(30\$mytable)
& 9:?(31\$mytable)
& out\$(!(30\$mytable))
& out\$(!(-169\$mytable)) { -169 mod 100 == 31 }
& out\$!mytable { still index 31 }
& tbl\$(mytable,0)
& (!mytable & out\$"mytable still exists"
| out\$"mytable is gone"
)
);
Output:
5
9
9
mytable is gone
## Boo
myArray as (int) = (1, 2, 3) // Size based on initialization
fixedArray as (int) = array(int, 1) // Given size(1 in this case)
myArray[0] = 10
myArray = myArray + fixedArray // Append arrays
print myArray[0]
## Brainf***
Note that Brainf*** does not natively support arrays, this example creates something that's pretty close, with access of elements at each index, altering elements, and changing size of list at runtime.
===========[
ARRAY DATA STRUCTURE
AUTHOR: Keith Stellyes
WRITTEN: June 2016
This is a zero-based indexing array data structure, it assumes the following
precondition:
>INDEX<|NULL|VALUE|NULL|VALUE|NULL|VALUE|NULL
(Where >< mark pointer position, and | separates addresses)
It relies heavily on [>] and [<] both of which are idioms for
finding the next left/right null
HOW INDEXING WORKS:
It runs a loop _index_ number of times, setting that many nulls
to a positive, so it can be skipped by the mentioned idioms.
Basically, it places that many "milestones".
EXAMPLE:
If we seek index 2, and our array is {1 , 2 , 3 , 4 , 5}
FINDING INDEX 2:
(loop to find next null, set to positive, as a milestone
decrement index)
index
2 |0|1|0|2|0|3|0|4|0|5|0
1 |0|1|1|2|0|3|0|4|0|5|0
0 |0|1|1|2|1|3|0|4|0|5|0
===========]
=======UNIT TEST=======
SET ARRAY {48 49 50}
>>++++++++++++++++++++++++++++++++++++++++++++++++>>
+++++++++++++++++++++++++++++++++++++++++++++++++>>
++++++++++++++++++++++++++++++++++++++++++++++++++
<<<<<<++ Move back to index and set it to 2
=======================
===RETRIEVE ELEMENT AT INDEX===
=ACCESS INDEX=
[>>[>]+[<]<-] loop that sets a null to a positive for each iteration
First it moves the pointer from index to first value
Then it uses a simple loop that finds the next null
it sets the null to a positive (1 in this case)
Then it uses that same loop reversed to find the first
null which will always be one right of our index
so we decrement our index
Finally we decrement pointer from the null byte to our
index and decrement it
>> Move pointer to the first value otherwise we can't loop
[>]< This will find the next right null which will always be right
of the desired value; then go one left
. Output the value (In the unit test this print "2"
[<[-]<] Reset array
===ASSIGN VALUE AT INDEX===
STILL NEED TO ADJUST UNIT TESTS
NEWVALUE|>INDEX<|NULL|VALUE etc
[>>[>]+[<]<-] Like above logic except it empties the value and doesn't reset
>>[>]<[-]
[<]< Move pointer to desired value note that where the index was stored
is null because of the above loop
[->>[>]+[<]<] If NEWVALUE is GREATER than 0 then decrement it & then find the
newly emptied cell and increment it
[>>[>]<+[<]<<-] Move pointer to first value find right null move pointer left
then increment where we want our NEWVALUE to be stored then
return back by finding leftmost null then decrementing pointer
twice then decrement our NEWVALUE cell
## C
Fixed size static array of integers with initialization:
int myArray2[10] = { 1, 2, 0 }; /* the rest of elements get the value 0 */
float myFloats[] ={1.2, 2.5, 3.333, 4.92, 11.2, 22.0 }; /* automatically sizes */
When no size is given, the array is automatically sized. Typically this is how initialized arrays are defined. When this is done, you'll often see a definition that produces the number of elements in the array, as follows.
#define MYFLOAT_SIZE (sizeof(myFloats)/sizeof(myFloats[0]))
When defining autosized multidimensional arrays, all the dimensions except the first (leftmost) need to be defined. This is required in order for the compiler to generate the proper indexing for the array.
long a2D_Array[3][5]; /* 3 rows, 5 columns. */
float my2Dfloats[][3] = {
1.0, 2.0, 0.0,
5.0, 1.0, 3.0 };
#define FLOAT_ROWS (sizeof(my2Dfloats)/sizeof(my2dFloats[0]))
When the size of the array is not known at compile time, arrays may be dynamically allocated to the proper size. The malloc(), calloc() and free() functions require the header stdlib.h.
int numElements = 10;
int *myArray = malloc(sizeof(int) * numElements); /* array of 10 integers */
if ( myArray != NULL ) /* check to ensure allocation succeeded. */
{
/* allocation succeeded */
/* at the end, we need to free the allocated memory */
free(myArray);
}
/* calloc() additionally pre-initializes to all zeros */
short *myShorts = calloc( numElements, sizeof(short)); /* array of 10 */
if (myShorts != NULL)....
Once allocated, myArray can be used as a normal array.
The first element of a C array is indexed with 0. To set a value:
myArray[0] = 1;
myArray[1] = 3;
And to retrieve it (e.g. for printing, provided that the stdio.h header was included for the printf function)
printf("%d\n", myArray[1]);
The array[index] syntax can be considered as a shortcut for *(index + array) and thus the square brackets are a commutative binary operator:
*(array + index) = 1;
printf("%d\n", *(array + index));
3[array] = 5;
There's no bounds check on the indexes. Negative indexing can be implemented as in the following.
#define XSIZE 20
double *kernel = malloc(sizeof(double)*2*XSIZE+1);
if (kernel) {
kernel += XSIZE;
for (ix=-XSIZE; ix<=XSIZE; ix++) {
kernel[ix] = f(ix);
....
free(kernel-XSIZE);
}
}
In C99, it is possible to declare arrays with a size that is only known at runtime (e.g. a number input by the user).
Typically dynamic allocation is used and the allocated array is sized to the maximum that might be needed. A additional variable is declared and used to maintain the current number of elements used. In C, arrays may be dynamically resized if they were allocated:
int *array = malloc (sizeof(int) * 20);
....
array = realloc(array, sizeof(int) * 40);
## ChucK
int array[0]; // instantiate int array
array << 1; // append item
array << 2 << 3; // append items
4 => array[3]; // assign element(4) to index(3)
5 => array.size; // resize
array.clear(); // clear elements
<<<array.size()>>>; // print in cosole array size
[1,2,3,4,5,6,7] @=> array;
array.popBack(); // Pop last element
## C++
Works with: C++11
C++ supports several types of array, depending on whether or not the size is known at compile time, and whether the array must be fixed-size or can grow.
std::array<T, N> is a fixed-size array of T objects. The size (N) must be known at compile time. It wraps a C array, and provides additional functionality and safety. Depending on how it is used, it may be dynamically allocated on the stack as needed, placed in read-only program memory at load time, or possibly may only exist during compilation and get optimized away, among other possibilities.
std::vector<T> is a resizable array of T objects. The memory for the array will be allocated from the heap (unless a custom allocator is used).
#include <array>
#include <vector>
// These headers are only needed for the demonstration
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
// This is a template function that works for any array-like object
template <typename Array>
void demonstrate(Array& array)
{
// Array element access
array[2] = "Three"; // Fast, but unsafe - if the index is out of bounds you
// get undefined behaviour
array.at(1) = "Two"; // *Slightly* less fast, but safe - if the index is out
// of bounds, an exception is thrown
// Arrays can be used with standard algorithms
std::reverse(begin(array), end(array));
std::for_each(begin(array), end(array),
[](typename Array::value_type const& element) // in C++14, you can just use auto
{
std::cout << element << ' ';
});
std::cout << '\n';
}
int main()
{
// Compile-time sized fixed-size array
auto fixed_size_array = std::array<std::string, 3>{ "One", "Four", "Eight" };
// If you do not supply enough elements, the remainder are default-initialized
// Dynamic array
auto dynamic_array = std::vector<std::string>{ "One", "Four" };
dynamic_array.push_back("Eight"); // Dynamically grows to accept new element
// All types of arrays can be used more or less interchangeably
demonstrate(fixed_size_array);
demonstrate(dynamic_array);
}
## C#
Example of array of 10 int types:
int[] numbers = new int[10];
Example of array of 3 string types:
string[] words = { "these", "are", "arrays" };
You can also declare the size of the array and initialize the values at the same time:
int[] more_numbers = new int[3]{ 21, 14 ,63 };
For Multi-Dimensional arrays you declare them the same except for a comma in the type declaration.
The following creates a 3x2 int matrix
int[,] number_matrix = new int[3,2];
As with the previous examples you can also initialize the values of the array, the only difference being each row in the matrix must be enclosed in its own braces.
string[,] string_matrix = { {"I","swam"}, {"in","the"}, {"freezing","water"} };
or
string[,] funny_matrix = new string[2,2]{ {"clowns", "are"} , {"not", "funny"} };
int[] array = new int[10];
array[0] = 1;
array[1] = 3;
Console.WriteLine(array[0]);
Dynamic
using System;
using System.Collections.Generic;
List<int> list = new List<int>();
list[0] = 2;
Console.WriteLine(list[0]);
## Ceylon
Works with: Ceylon version 1.3.0
import ceylon.collection {
ArrayList
}
shared void run() {
// you can get an array from the Array.ofSize named constructor
value array = Array.ofSize(10, "hello");
value a = array[3];
print(a);
array[4] = "goodbye";
print(array);
// for a dynamic list import ceylon.collection in your module.ceylon file
value list = ArrayList<String>();
list.push("hello");
list.push("hello again");
print(list);
}
## Clean
Array denotations are overloaded in Clean, therefore we explicitly specify the types. There are lazy, strict, and unboxed array.
### Lazy array
Create a lazy array of strings using an array denotation.
array :: {String}
array = {"Hello", "World"}
Create a lazy array of floating point values by sharing a single element.
array :: {Real}
array = createArray 10 3.1415
Create a lazy array of integers using an array (and also a list) comprehension.
array :: {Int}
array = {x \\ x <- [1 .. 10]}
### Strict array
Create a strict array of integers.
array :: {!Int}
array = {x \\ x <- [1 .. 10]}
### Unboxed array
Create an unboxed array of characters, also known as String.
array :: {#Char}
array = {x \\ x <- ['a' .. 'z']}
## Clipper
Clipper arrays aren't divided to fixed-length and dynamic. Even if we declare it with a certain dimensions, it can be resized in the same way as it was created dynamically. The first position in an array is 1, not 0, as in some other languages.
// Declare and initialize two-dimensional array
Local arr1 := { { "NITEM","N",10,0 }, { "CONTENT","C",60,0} }
// Create an empty array
Local arr2 := {}
// Declare three-dimensional array
Local arr3[2,100,3]
// Create an array
Local arr4 := Array(50)
// Array can be dynamically resized:
arr4 := ASize( arr4, 80 )
Items, including nested arrays, can be added to existing array, deleted from it, assigned to it
// Adding new item to array, its size is incremented
Aadd( arr1, { "LBASE","L",1,0 } )
// Delete the first item of arr3, The size of arr3 remains the same, all items are shifted to one position, the last item is replaced by Nil:
ADel( arr1, 1 )
// Assigning a value to array item
arr3[1,1,1] := 11.4
Retrieve items of an array:
x := arr3[1,10,2]
// The retrieved item can be nested array, in this case it isn't copied, the pointer to it is assigned
There is a set of functions to manage arrays in Clipper, including the following:
// Fill the 20 items of array with 0, starting from 5-th item:
AFill( arr4, 0, 5, 20 )
//Copy 10 items from arr4 to arr3[2], starting from the first position:
ACopy( arr4, arr3[2], 1, 10 )
//Duplicate the whole or nested array:
arr5 := AClone( arr1 )
arr6 := AClone( arr1[3] )
## Clojure
;clojure is a language built with immutable/persistent data structures. there is no concept of changing what a vector/list
;is, instead clojure creates a new array with an added value using (conj...)
;in the example below the my-list does not change.
user=> (def my-list (list 1 2 3 4 5))
user=> my-list
(1 2 3 4 5)
user=> (first my-list)
1
user=> (nth my-list 3)
4
user=> (conj my-list 100) ;adding to a list always adds to the head of the list
(100 1 2 3 4 5)
user=> my-list ;it is impossible to change the list pointed to by my-list
(1 2 3 4 5)
user=> (def my-new-list (conj my-list 100))
user=> my-new-list
(100 1 2 3 4 5)
user=> (cons 200 my-new-list) ;(cons makes a new list, (conj will make a new object of the same type as the one it is given
(200 100 1 2 3 4 5)
user=> (def my-vec [1 2 3 4 5 6])
user=> (conj my-vec 300) ;adding to a vector always adds to the end of the vector
[1 2 3 4 5 6 300]
## COBOL
In COBOL, arrays are called tables. Also, indexes begin from 1.
IDENTIFICATION DIVISION.
PROGRAM-ID. arrays.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 fixed-length-table.
03 fixed-table-elt PIC X OCCURS 5 TIMES.
01 table-length PIC 9(5) VALUE 1.
01 variable-length-table.
03 variable-table-elt PIC X OCCURS 1 TO 5 TIMES
DEPENDING ON table-length.
01 initial-value-area.
03 initial-values.
05 FILLER PIC X(10) VALUE "One".
05 FILLER PIC X(10) VALUE "Two".
05 FILLER PIC X(10) VALUE "Three".
03 initial-value-table REDEFINES initial-values.
05 initial-table-elt PIC X(10) OCCURS 3 TIMES.
01 indexed-table.
03 indexed-elt PIC X OCCURS 5 TIMES
INDEXED BY table-index.
PROCEDURE DIVISION.
*> Assigning the contents of an entire table.
MOVE "12345" TO fixed-length-table
*> Indexing an array (using an index)
MOVE 1 TO table-index
MOVE "1" TO indexed-elt (table-index)
*> Pushing a value into a variable-length table.
ADD 1 TO table-length
MOVE "1" TO variable-table-elt (2)
GOBACK
.
## CoffeeScript
array1 = []
array1[0] = "Dillenidae"
array1[1] = "animus"
array1[2] = "Kona"
alert "Elements of array1: " + array1 # Dillenidae,animus,Kona
array2 = ["Cepphus", "excreta", "Gansu"]
alert "Value of array2[1]: " + array2[1] # excreta
## ColdFusion
Creating a one-dimensional Array:
<cfset arr1 = ArrayNew(1)>
Creating a two-dimensional Array in CFScript:
<cfscript>
arr2 = ArrayNew(2);
</cfscript>
ColdFusion Arrays are NOT zero-based, they begin at index 1
## Common Lisp
(let ((array (make-array 10)))
(setf (aref array 0) 1
(aref array 1) 3)
(print array))
Dynamic
(let ((array (make-array 0 :adjustable t :fill-pointer 0)))
(vector-push-extend 1 array)
(vector-push-extend 3 array)
(setf (aref array 0) 2)
(print array))
Creates a one-dimensional array of length 10. The initial contents are undefined.
(make-array 10)
Creates a two-dimensional array with dimensions 10x20.
(make-array '(10 20))
make-array may be called with a number of optional arguments.
; Makes an array of 20 objects initialized to nil
(make-array 20 :initial-element nil)
; Makes an integer array of 4 elements containing 1 2 3 and 4 initially which can be resized
(make-array 4 :element-type 'integer :initial-contents '(1 2 3 4) :adjustable t)
## Component Pascal
An arrays in Component Pascal are started from zero index.
MODULE TestArray;
(* Implemented in BlackBox Component Builder *)
IMPORT Out;
(* Static array *)
PROCEDURE DoOneDim*;
CONST M = 5;
VAR a: ARRAY M OF INTEGER;
BEGIN
a[0] := 100; (* set first element's value of array a to 100 *)
a[M-1] := -100; (* set M-th element's value of array a to -100 *)
Out.Int(a[0], 0); Out.Ln;
Out.Int(a[M-1], 0); Out.Ln;
END DoOneDim;
PROCEDURE DoTwoDim*;
VAR b: ARRAY 5, 4 OF INTEGER;
BEGIN
b[1, 2] := 100; (* second row, third column element *)
b[4, 3] := -100; (* fifth row, fourth column element *)
Out.Int(b[1, 2], 0); Out.Ln;
Out.Int(b[4, 3], 0); Out.Ln;
END DoTwoDim;
END TestArray.
## Computer/zero Assembly
An array is simply a sequence of memory addresses. If we have an array beginning at address ary, we can access element ${\displaystyle n}$ (zero-indexed) using an instruction of the form LDA ary+n (or STA ary+n, ADD ary+n, SUB ary+n). Generating this instruction will often involve the use of self-modifying code: we start with an instruction like LDA ary, add ${\displaystyle n}$ to it, store it back, and execute it.
It is often convenient to be able to iterate through an array—which means knowing where the array ends. There are two easy ways to do this: fixed-length arrays and zero-terminated arrays. As an illustration, we shall find the sum of an array of the first ten positive integers using each technique.
### Fixed-length array
We have finished iterating through the array when the next load instruction would be LDA ary+length(ary).
STA sum
SUB end
BRZ done
done: LDA sum
STP
one: 1
end: LDA ary+10
sum: 0
ary: 1
2
3
4
5
6
7
8
9
10
BRZ done
STA sum
done: LDA sum
STP
one: 1
sum: 0
ary: 1
2
3
4
5
6
7
8
9
10
0
## D
// All D arrays are capable of bounds checks.
import std.stdio, core.stdc.stdlib;
import std.container: Array;
void main() {
// GC-managed heap allocated dynamic array:
auto array1 = new int[1];
array1[0] = 1;
array1 ~= 3; // append a second item
// array1[10] = 4; // run-time error
writeln("A) Element 0: ", array1[0]);
writeln("A) Element 1: ", array1[1]);
// Stack-allocated fixed-size array:
int[5] array2;
array2[0] = 1;
array2[1] = 3;
// array2[2] = 4; // compile-time error
writeln("B) Element 0: ", array2[0]);
writeln("B) Element 1: ", array2[1]);
// Stack-allocated dynamic fixed-sized array,
// length known only at run-time:
int n = 2;
int[] array3 = (cast(int*)alloca(n * int.sizeof))[0 .. n];
array3[0] = 1;
array3[1] = 3;
// array3[10] = 4; // run-time error
writeln("C) Element 0: ", array3[0]);
writeln("C) Element 1: ", array3[1]);
// Phobos-defined heap allocated not GC-managed array:
Array!int array4;
array4.length = 2;
array4[0] = 1;
array4[1] = 3;
// array4[10] = 4; // run-time exception
writeln("D) Element 0: ", array4[0]);
writeln("D) Element 1: ", array4[1]);
}
Output:
A) Element 0: 1
A) Element 1: 3
B) Element 0: 1
B) Element 1: 3
C) Element 0: 1
C) Element 1: 3
D) Element 0: 1
D) Element 1: 3
One more kind of built-in array:
import std.stdio, core.simd;
void main() {
// Stack-allocated vector for SIMD registers:
ubyte16 vector5;
vector5.array[0] = 1;
vector5.array[1] = 3;
// vector5.array[17] = 4; // Compile-time error.
writeln("E) Element 0: ", vector5.array[0]);
writeln("E) Element 1: ", vector5.array[1]);
}
Output:
E) Element 0: 1
E) Element 1: 3
## Dao
# use [] to create numeric arrays of int, float, double or complex types:
a = [ 1, 2, 3 ] # a vector
b = [ 1, 2; 3, 4 ] # a 2X2 matrix
# use {} to create normal arrays of any types:
c = { 1, 2, 'abc' }
d = a[1]
e = b[0,1] # first row, second column
f = c[1]
## Déjà Vu
In Déjà Vu, the relevant datatype is called list, which is basically a stack with random element access for getting and setting values.
#create a new list
local :l []
#add something to it
push-to l "Hi"
#add something else to it
push-to l "Boo"
#the list could also have been built up this way:
local :l2 [ "Hi" "Boo" ]
#this prints 2
!print len l
#this prints Hi
!print get-from l 0
#this prints Boo
!print pop-from l
## Delphi
This example creates a static and dynamic array, asks for a series of numbers storing them in the static one, puts in the dynamic one the numbers in reverse order, concatenates the number in two single string variables and display those strings in a popup window.
procedure TForm1.Button1Click(Sender: TObject);
var
StaticArray: array[0..9] of Integer;
DynamicArray: array of Integer;
StaticArrayText,
DynamicArrayText: string;
lcv: Integer;
begin
// Setting the length of the dynamic array the same as the static one
SetLength(DynamicArray, Length(StaticArray));
// Asking random numbers storing into the static array
for lcv := 0 to Pred(Length(StaticArray)) do
begin
StaticArray[lcv] := StrToInt(
InputBox('Random number',
'Enter a random number for position',
IntToStr(Succ(lcv))));
end;
// Storing entered numbers of the static array in reverse order into the dynamic
for lcv := 0 to Pred(Length(StaticArray)) do
DynamicArray[Pred(Length(DynamicArray)) - lcv] := StaticArray[lcv];
// Concatenating the static and dynamic array into a single string variable
for lcv := 0 to Pred(Length(StaticArray)) do
begin
StaticArrayText := StaticArrayText + IntToStr(StaticArray[lcv]);
DynamicArrayText := DynamicArrayText + IntToStr(DynamicArray[lcv]);
end;
// Displaying both arrays (#13#10 = Carriage Return/Line Feed)
ShowMessage(StaticArrayText + #13#10 + DynamicArrayText);
end;
## DWScript
// dynamic array, extensible, this a reference type
var d : array of Integer;
d.Add(1); // has various methods to add, delete, etc.
// read and write elements by index
item := d[5];
d[6] := item+1;
// static, fixed-size array, arbitrary lower-bound, this is a value type
var s : array [2..4] of Integer;
// inline array constructor, works for both static and dynamic arrays
s := [1, 2, 3];
## E
E's collection library emphasizes providing both mutable and immutable collections. The relevant array-like types are ConstList and FlexList.
Literal lists are ConstLists.
? def empty := []
# value: []
? def numbers := [1,2,3,4,5]
# value: [1, 2, 3, 4, 5]
? numbers.with(6)
# value: [1, 2, 3, 4, 5, 6]
? numbers + [4,3,2,1]
# value: [1, 2, 3, 4, 5, 4, 3, 2, 1]
Note that each of these operations returns a different list object rather than modifying the original. You can, for example, collect values:
? var numbers := []
# value: []
? numbers := numbers.with(1)
# value: [1]
? numbers with= 2 # shorthand for same
# value: [1, 2]
FlexLists can be created explicitly, but are typically created by diverging another list. A ConstList can be gotten from a FlexList by snapshot.
? def flex := numbers.diverge()
# value: [1, 2].diverge()
? flex.push(-3)
? flex
# value: [1, 2, -3].diverge()
? numbers
# value: [1, 2]
? flex.snapshot()
# value: [1, 2, -3]
Creating a FlexList with a specific size, generic initial data, and a type restriction:
([0] * 100).diverge(int) # contains 100 zeroes, can only contain integers
Note that this puts the same value in every element; if you want a collection of some distinct mutable objects, see N distinct objects#E.
In accordance with its guarantees of determinism, you can never have an uninitialized FlexList in E.
## EGL
Arrays in EGL are 1-based, so the first element of an array is placed in element [1].
Fixed-length array
array int[10]; //optionally, add a braced list of values. E.g. array int[10]{1, 2, 3};
array[1] = 42;
SysLib.writeStdout(array[1]);
Output:
42
Dynamic array
array int[0]; // Array declared without elements.
array.appendElement(11); // Add an element to the array and provide a value at the samen time.
array.appendElement(new int{}); // Add an element with the correct type, but without a value.
array[2] = 18; // Set the value of the added element.
SysLib.writeStdout(array[1]);
SysLib.writeStdout(array[2]);
Output:
11
18
## Eiffel
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
make
-- Run application.
do
-- initialize the array, index starts at 1 (not zero) and prefill everything with the letter z
create my_static_array.make_filled ("z", 1, 50)
my_static_array.put ("a", 1)
my_static_array.put ("b", 2)
my_static_array [3] := "c"
print (my_static_array.at(1) + "%N")
print (my_static_array.at(2) + "%N")
print (my_static_array [3] + "%N")
-- in Eiffel static arrays can be resized in three ways
my_static_array.force ("c", 51) -- forces 'c' in position 51 and resizes the array to that size (now 51 places)
my_static_array.automatic_grow -- adds 50% more indices (having now 76 places)
my_static_array.grow (100) -- resizes the array to 100 places
end
my_static_array: ARRAY [STRING]
end
## Elena
Static array
#var aStaticArray := (1, 2, 3).
Generic array
#var anArray := system'Array new &length:3.
[email protected] := 1.
[email protected] := 2.
[email protected] := 3.
Stack allocated typed array
#var(int:3)aStackAllocatedArray.
[email protected] := 1.
[email protected] := 2.
[email protected] := 3.
Dynamic array
#var aDynamicArray := ArrayList new.
[email protected] := 3.
Printing an element
system'console writeLine:([email protected]).
system'console writeLine:([email protected]).
system'console writeLine:([email protected]).
## Elixir
The elixir language has array-like structures called tuples. The values of tuples occur sequentially in memory, and can be of any type. Tuples are represented with curly braces:
ret = {:ok, "fun", 3.1415}
Elements of tuples are indexed numerically, starting with zero.
elem(ret, 1) == "fun"
elem(ret, 0) == :ok
put_elem(ret, 2, "pi") # => {:ok, "fun", "pi"}
ret == {:ok, "fun", 3.1415}
Elements can be appended to tuples with Tuple.append/2, which returns a new tuple, without having modified the tuple given as an argument.
Tuple.append(ret, 3.1415) # => {:ok, "fun", "pie", 3.1415}
New tuple elements can be inserted with Tuple.insert/3, which returns a new tuple with the given value inserted at the indicated position in the tuple argument.
Tuple.insert_at(ret, 1, "new stuff") # => {:ok, "new stuff", "fun", "pie"}
Elixir also has structures called lists, which can contain values of any type, and are implemented as linked lists. Lists are represented with square brackets:
[ 1, 2, 3 ]
Lists can be indexed, appended, added, subtracted, and list elements can be replaced, updated, and deleted. In all cases, new lists are returned without affecting the list being operated on.
my_list = [1, :two, "three"]
my_list ++ [4, :five] # => [1, :two, "three", 4, :five]
List.insert_at(my_list, 0, :cool) # => [:cool, 1, :two, "three"]
List.replace_at(my_list, 1, :cool) # => [1, :cool, "three"]
List.delete(my_list, :two) # => [1, "three"]
my_list -- ["three", 1] # => [:two]
my_list # => [1, :two, "three"]
Lists have a head, being the first element, and a tail, which are all the elements of the list following the head.
iex(1)> fruit = [:apple, :banana, :cherry]
[:apple, :banana, :cherry]
iex(2)> hd(fruit)
:apple
iex(3)> tl(fruit)
[:banana, :cherry]
iex(4)> hd(fruit) == :apple
true
iex(5)> tl(fruit) == [:banana, :cherry]
true
## Erlang
%% Create a fixed-size array with entries 0-9 set to 'undefined'
A0 = array:new(10).
10 = array:size(A0).
%% Create an extendible array and set entry 17 to 'true',
%% causing the array to grow automatically
A1 = array:set(17, true, array:new()).
18 = array:size(A1).
%% Read back a stored value
true = array:get(17, A1).
%% Accessing an unset entry returns the default value
undefined = array:get(3, A1).
%% Accessing an entry beyond the last set entry also returns the
%% default value, if the array does not have fixed size
undefined = array:get(18, A1).
%% "sparse" functions ignore default-valued entries
A2 = array:set(4, false, A1).
[{4, false}, {17, true}] = array:sparse_to_orddict(A2).
%% An extendible array can be made fixed-size later
A3 = array:fix(A2).
%% A fixed-size array does not grow automatically and does not
%% allow accesses beyond the last set entry
{'EXIT',{badarg,_}} = (catch array:set(18, true, A3)).
{'EXIT',{badarg,_}} = (catch array:get(18, A3)).
## ERRE
To declare array variables (with their associated type):
DIM A%[100] ! integer array
DIM S\$[50] ! string array
DIM R[50] ! real array
DIM R#[70] ! long real array
Index starts from 0: you can start from 1 by using a pragma directive
!\$BASE=1
Subscripts can be a constant like:
CONST MX=100
.......
DIM A%[MX]
ERRE arrays are static (known at compile-time) but you can declare dynamic arrays (subscripts depends from a user' input):
!\$DYNAMIC
DIM A%[0] ! dummy declaration
.......
BEGIN
INPUT(NUM)
!\$DIM A%[NUM]
.......
You can also redimensioning arrays with ERASE clause:
!\$RCODE="ERASE A%"
INPUT(NUM2)
!\$DIM A%[NUM2]
Unfortunately there is no PRESERVE clause, so after an ERASE all array values are lost.
Values can be assigned to an array by a DATA..READ statements, by an INPUT or by normal assignment:
DATA(0,1,2,3,4,5,6,7,8,9,10)
FOR I%=0 TO 10 DO
END FOR
It's possible to assign an array to another (same type and dimensions) with
B%[]=A%[]
Arrays are global object in an ERRE module: in the next revision there will be a LOCAL DIM statement for "local arrays".
## Euphoria
--Arrays task for Rosetta Code wiki
--User:Lnettnay
atom dummy
--Arrays are sequences
-- single dimensioned array of 10 elements
sequence xarray = repeat(0,10)
xarray[5] = 5
dummy = xarray[5]
? dummy
--2 dimensional array
--5 sequences of 10 elements each
sequence xyarray = repeat(repeat(0,10),5)
xyarray[3][6] = 12
dummy = xyarray[3][6]
? dummy
--dynamic array use (all sequences can be modified at any time)
sequence dynarray = {}
for x = 1 to 10 do
dynarray = append(dynarray, x * x)
end for
? dynarray
for x = 1 to 10 do
dynarray = prepend(dynarray, x)
end for
? dynarray
Output:
5
12
{1,4,9,16,25,36,49,64,81,100}
{10,9,8,7,6,5,4,3,2,1,1,4,9,16,25,36,49,64,81,100}
## F#
Fixed-length arrays:
> Array.create 6 'A';;
val it : char [] = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|]
> Array.init 8 (fun i -> i * 10) ;;
val it : int [] = [|0; 10; 20; 30; 40; 50; 60; 70|]
> let arr = [|0; 1; 2; 3; 4; 5; 6 |] ;;
val arr : int [] = [|0; 1; 2; 3; 4; 5; 6|]
> arr.[4];;
val it : int = 4
> arr.[4] <- 65 ;;
val it : unit = ()
> arr;;
val it : int [] = [|0; 1; 2; 3; 65; 5; 6|]
Dynamic arrays:
If dynamic arrays are needed, it is possible to use the .NET class System.Collections.Generic.List<'T> which is aliased as Microsoft.FSharp.Collections.ResizeArray<'T>:
> let arr = new ResizeArray<int>();;
val arr : ResizeArray<int>
val it : unit = ()
> arr.[0];;
val it : int = 42
> arr.[0] <- 13;;
val it : unit = ()
> arr.[0];;
val it : int = 13
> arr.[1];;
> System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index ...
> arr;;
val it : ResizeArray<int> = seq [13]
## Factor
(cleave applies all the quotations to the initial argument (the array)) This demonstrates array litterals and writing/reading to the array
Directly in the listener :
{ 1 2 3 }
{
[ "The initial array: " write . ]
[ [ 42 1 ] dip set-nth ]
[ "Modified array: " write . ]
[ "The element we modified: " write [ 1 ] dip nth . ]
} cleave
The initial array: { 1 2 3 }
Modified array: { 1 42 3 }
The element we modified: 42
Arrays of arbitrary length can be created with the <array> word :
( scratchpad - auto ) 10 42 <array> .
{ 42 42 42 42 42 42 42 42 42 42 }
Arrays can contain different types :
{ 1 "coucou" f [ ] }
Arrays of growable length are called Vectors.
V{ 1 2 3 }
{
[ "The initial vector: " write . ]
[ [ 42 ] dip push ]
[ "Modified vector: " write . ]
} cleave
The initial vector: V{ 1 2 3 }
Modified vector: V{ 1 2 3 42 }
Vectors can also be used with set-nth and nth.
( scratchpad - auto ) V{ } [ [ 5 5 ] dip set-nth ] [ . ] bi
V{ 0 0 0 0 0 5 }
## FBSL
Various types of FBSL's BASIC arrays are listed below:
#APPTYPE CONSOLE
DIM v[-1 TO 1] AS VARIANT ' static Variant
v[-1] = -1
v[0] = "zero"
v[1] = !1.0
FOR EACH DIM e IN v
PRINT e, " ";
NEXT
PRINT
DIM i[-1 TO 1] AS INTEGER ' static strong-type Integer/Quad/Single/Double/String
i[-1] = -1
i[0] = "zero"
i[1] = !1
FOR EACH e IN i
PRINT e, " ";
NEXT
PRINT
DIM d[] AS INTEGER ' dynamic growable strong-type Integer/Quad/Single/Double/String
d[] = -1
d[] = "zero"
d[] = !1
FOR EACH e IN d
PRINT e, " ";
NEXT
PRINT
DIM a[] AS VARIANT = {-1, "zero", !1} ' dynamic growable Variant w/ anonymous array initialization
FOR EACH e IN a
PRINT e, " ";
NEXT
PRINT
FOR EACH e IN {-1, "zero", !1} ' anonymous Variant
PRINT e, " ";
NEXT
PRINT
PAUSE
Output:
-1 zero 1.000000
-1 0 1
-1 0 1
-1 zero 1.000000
-1 zero 1.000000
Press any key to continue...
FBSL's Dynamic C supports static and dynamic initialized arrays. Dynamic variable-length arrays are not currently supported.
## Forth
Forth has a variety of ways to allocate arrays of data as contiguous blocks of memory, though it has no built-in array handling words, favoring pointer arithmetic.
For example, a static array of 10 cells in the dictionary, 5 initialized and 5 uninitialized:
create MyArray 1 , 2 , 3 , 4 , 5 , 5 cells allot
here constant MyArrayEnd
30 MyArray 7 cells + !
MyArray 7 cells + @ . \ 30
: .array MyArrayEnd MyArray do I @ . cell +loop ;
: array ( n -- )
create
dup , \ remember size at offset 0
dup cells here swap 0 fill \ fill cells with zero
cells allot \ allocate memory
does> ( i addr -- )
swap 1+ cells + ; \ hide offset=0 to index [0..n-1]
: [size] -1 ;
10 array MyArray
30 7 MyArray !
7 MyArray @ . \ 30
: 5fillMyArray 5 0 do I I MyArray ! loop ;
: .MyArray [size] MyArray @ 0 do I MyArray @ . loop ;
.MyArray \ 0 0 0 0 0 0 30 0 0 0
5fillMyArray
.MyArray \ 1 2 3 4 5 0 30 0 0 0
: array create dup , dup cells here swap 0 fill cells allot ;
: [size] @ ;
: [cell] 1+ cells + ; \ hide offset=0 to index [0..n-1]
10 array MyArray
30 MyArray 7 [cell] !
MyArray 7 [cell] @ . \ 30
: 5fillMyArray 5 0 do I MyArray I [cell] ! loop ;
: .MyArray MyArray [size] 0 do MyArray I [cell] @ . loop ;
.MyArray \ 0 0 0 0 0 0 30 0 0 0
5fillMyArray
.MyArray \ 1 2 3 4 5 0 30 0 0 0
## Fortran
Works with: Fortran version 90 and later
Basic array declaration:
integer a (10)
integer :: a (10)
integer, dimension (10) :: a
Arrays are one-based. These declarations are equivalent:
integer, dimension (10) :: a
integer, dimension (1 : 10) :: a
Other bases can be used:
integer, dimension (0 : 9) :: a
Arrays can have any type (intrinsic or user-defined), e.g.:
real, dimension (10) :: a
type (my_type), dimension (10) :: a
Multidimensional array declaration:
integer, dimension (10, 10) :: a
integer, dimension (10, 10, 10) :: a
Allocatable array declaration:
integer, dimension (:), allocatable :: a
integer, dimension (:, :), allocatable :: a
Array allocation:
allocate (a (10))
allocate (a (10, 10))
Array deallocation:
deallocate (a)
Array initialisation:
integer, dimension (10) :: a = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)
integer :: i
integer, dimension (10) :: a = (/(i * i, i = 1, 10)/)
integer, dimension (10) :: a = 0
integer :: i
integer, dimension (10, 10) :: a = reshape ((/(i * i, i = 1, 100)/), (/10, 10/))
Constant array declaration:
integer :: i
integer, dimension (10), parameter :: a = (/(i * i, i = 1, 10)/)
Element assignment:
a (1) = 1
a (1, 1) = 1
Array assignment:
a = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)
a = (/(i * i, i = 1, 10)/)
a = reshape ((/(i * i, i = 1, 100)/), (/10, 10/))
a = 0
Array section assignment:
a (:) = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)
a (1 : 5) = (/1, 2, 3, 4, 5/)
a (: 5) = (/1, 2, 3, 4, 5/)
a (6 :) = (/1, 2, 3, 4, 5/)
a (1 : 5) = (/(i * i, i = 1, 10)/)
a (1 : 5)= 0
a (1, :)= (/(i * i, i = 1, 10)/)
a (1 : 5, 1)= (/(i * i, i = 1, 5)/)
Element retrieval:
i = a (1)
Array section retrieval:
a = b (1 : 10)
Size retrieval:
i = size (a)
Size along a single dimension retrieval:
i = size (a, 1)
Bounds retrieval:
i_min = lbound (a)
i_max = ubound (a)
Bounds of a multidimensional array retrieval:
a = ubound (b)
## FreeBASIC
This info only applies for the default setting fb. For the other modes [fblite, qb, deprecated] other keywords and restrictions apply. Consult the FreeBASIC manual for those modes.
Parts of the info was taken from the FreeBASIC manual.
Arrays limits Maximum Subscript Range [-2147483648, +2147483647] [*] Maximum Elements per Dimension +2147483647 [*] Minimum/Maximum Dimensions 1/9 Maximum Size (in bytes) +2147483647 [*]
[*] All runtime library array procedures take and produce Integer values for subscripts and indexes. The actual limits will vary (smaller) with the number of dimensions, element size, storage location and/or platform.
Every Data Type that is allowed in FreeBASIC can be used for an array. (Integer, Double, String, UDT etc.)
Static Specifies static storage arrays; they are allocated at program startup and deallocated upon exit. Shared makes module-level array's visible inside Subs and Functions. Dim fixed length. ReDim variable length. Preserve can only be used With ReDim. If the array is resized, data is not reset but is preserved. Erase statement to erase arrays, clear the elements.
Fixed length array are created in the stack Space, if this space is to small the compiler will issue a warning. "Array too large for stack, consider making it var-len or Shared" You can make the array var-len by using Redim or use Dim Shared instead of Dim.
By default the bounds check is off, you can add the checks by adding the command line option -exx.(will slow the program down)
The default lower bound is always 0
' compile with: FBC -s console.
' compile with: FBC -s console -exx to have boundary checks.
Dim As Integer a(5) ' from s(0) to s(5)
Dim As Integer num = 1
Dim As String s(-num To num) ' s1(-1), s1(0) and s1(1)
Static As UByte c(5) ' create a array with 6 elements (0 to 5)
'dimension array and initializing it with Data
Dim d(1 To 2, 1 To 5) As Integer => {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}}
Print " The first dimension has a lower bound of"; LBound(d);_
" and a upper bound of"; UBound(d)
Print " The second dimension has a lower bound of"; LBound(d,2);_
" and a upper bound of"; UBound(d,2)
Print : Print
Dim Shared As UByte u(0 To 3) ' make a shared array of UByte with 4 elements
Dim As UInteger pow() ' make a variable length array
' you must Dim the array before you can use ReDim
ReDim pow(num) ' pow now has 1 element
pow(num) = 10 ' lets fill it with 10 and print it
Print " The value of pow(num) = "; pow(num)
ReDim pow(10) ' make pow a 10 element array
Print
Print " Pow now has"; UBound(pow) - LBound(pow) +1; " elements"
' the value of pow(num) is gone now
Print " The value of pow(num) = "; pow(num); ", should be 0"
Print
For i As Integer = LBound(pow) To UBound(pow)
pow(i) = i * i
Print pow(i),
Next
Print:Print
ReDim Preserve pow(3 To 7)
' the first five elements will be preserved, not elements 3 to 7
Print
Print " The lower bound is now"; LBound(pow);_
" and the upper bound is"; UBound(pow)
Print " Pow now has"; UBound(pow) - LBound(pow) +1; " elements"
Print
For i As Integer = LBound(pow) To UBound(pow)
Print pow(i),
Next
Print : Print
'erase the variable length array
Erase pow
Print " The lower bound is now"; LBound(pow);_
" and the upper bound is "; UBound(pow)
Print " If the lower bound is 0 and the upper bound is -1 it means,"
Print " that the array has no elements, it's completely removed"
Print : Print
'erase the fixed length array
Print " Display the contents of the array d"
For i As Integer = 1 To 2 : For j As Integer = 1 To 5
Print d(i,j);" ";
Next : Next : Print : Print
Erase d
Print " We have erased array d"
Print " The first dimension has a lower bound of"; LBound(d);_
" and a upper bound of"; UBound(d)
Print " The second dimension has a lower bound of"; LBound(d,2);_
" and a upper bound of"; UBound(d,2)
Print
For i As Integer = 1 To 2 : For j As Integer = 1 To 5
Print d(i,j);" ";
Next : Next
Print
Print " The elements self are left untouched but there content is set to 0"
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
Output:
The first dimension has a lower bound of 1 and a upper bound of 2
The second dimension has a lower bound of 1 and a upper bound of 5
The value of pow(num) = 10
Pow now has 11 elements
The value of pow(num) = 0, should be 0
0 1 4 9 16
25 36 49 64 81
100
The lower bound is now 3 and the upper bound is 7
Pow now has 5 elements
0 1 4 9 16
The lower bound is now 0 and the upper bound is -1
If the lower bound is 0 and the upper bound is -1 it means,
that the array has no elements, it completely removed
Display the contents of the array d
1 2 3 4 5 1 2 3 4 5
We have erased array d
The first dimension has a lower bound of 1 and a upper bound of 2
The second dimension has a lower bound of 1 and a upper bound of 5
0 0 0 0 0 0 0 0 0 0
The elements self are left untouched but there content is set to 0
## Frink
In Frink, all arrays are dynamically resizable. Arrays can be created as literals or using new array
a = new array
[email protected] = 10
[email protected] = 20
println[[email protected]]
b = [1, 2, 3]
## Futhark
Multidimensional regular arrays are a built-in datatype in Futhark. They can be written as array literals:
[1, 2, 3]
Or created by an assortment of built-in functions:
replicate 5 3 == [3,3,3,3,3]
iota 5 = [0,1,2,3,4]
Uniqueness types are used to permit in-place updates without violating referential transparency. For example, we can write a function that writes an element to a specific index of an array as such:
fun update(as: *[]int, i: int, x: int): []int =
let as[i] = x
in x
Semantically the update function returns a new array, but the compiler is at liberty to re-use the memory where array as is stored, rather than create a copy as is normally needed in pure languages. Whenever the compiler encounters a call update(as,i,x), it checks that the as is not used again. This prevents the in-place update from being observable, except through the return value of modify.
## Gambas
In Gambas, there is no need to dimension arrays. The first element of an array is numbered zero, and the DIM statement is optional and can be omitted:
DIM mynumbers AS INTEGER[]
myfruits AS STRING[]
mynumbers[0] = 1.5
mynumbers[1] = 2.3
myfruits[0] = "apple"
myfruits[1] = "banana"
## GAP
# Arrays are better called lists in GAP. Lists may have elements of mixed types, e\$
v := [ 10, 7, "bob", true, [ "inner", 5 ] ];
# [ 10, 7, "bob", true, [ "inner", 5 ] ]
# List index runs from 1 to Size(v)
v[1];
# 10
v[0];
# error
v[5];
# [ "inner", 5 ]
v[6];
# error
# One can assign a value to an undefined element
v[6] := 100;
# Even if it's not after the last: a list may have undefined elements
v[10] := 1000;
v;
# [ 10, 7, "bob", true, [ "inner", 5 ], 100,,,, 1000 ]
# And one can check for defined values
IsBound(v[10]);
# true
IsBound(v[9]);
# false
# Size of the list
Size(v);
# 10
# Appending a list to the end of another
Append(v, [ 8, 9]);
v;
# [ 10, 7, "bob", true, [ "inner", 5 ], 100,,,, 1000, 8, 9 ]
# Adding an element at the end
v;
# [ 10, 7, "bob", true, [ "inner", 5 ], 100,,,, 1000, 8, 9, "added" ]
## GML
### 1-Dimensional Array Examples
#### Example of Fixed Length Array
Array containing a space (" "), "A", "B", and "C":
array[0] = ' '
array[1] = 'A'
array[2] = 'B'
array[3] = 'C'
#### Example of Arbitrary Length Array
Array containing the set of all natural numbers from 1 through k:
for(i = 0; i < k; i += 1)
array[i] = i + 1
### 2-Dimensional Array Examples
#### Example of Fixed Length Array
Array containing the multiplication table of 1 through 4 by 1 through 3:
array[1,1] = 1
array[1,2] = 2
array[1,3] = 3
array[1,4] = 4
array[2,1] = 2
array[2,2] = 4
array[2,3] = 6
array[2,4] = 8
array[3,1] = 3
array[3,2] = 6
array[3,3] = 9
array[3,4] = 12
#### Example of Arbitrary Length Array
Array containing the multiplication table of 1 through k by 1 through h:
for(i = 1; i <= k; i += 1)
for(j = 1; j <= h; j += 1)
array[i,j] = i * j
## Go
package main
import (
"fmt"
)
func main() {
// creates an array of five ints.
// specified length must be a compile-time constant expression.
// this allows compiler to do efficient bounds checking.
var a [5]int
// since length is compile-time constant, len() is a compile time constant
// and does not have the overhead of a function call.
fmt.Println("len(a) =", len(a))
// elements are always initialized to 0
fmt.Println("a =", a)
// assign a value to an element. indexing is 0 based.
a[0] = 3
fmt.Println("a =", a)
// retrieve element value with same syntax
fmt.Println("a[0] =", a[0])
// a slice references an underlying array
s := a[:4] // this does not allocate new array space.
fmt.Println("s =", s)
// slices have runtime established length and capacity, but len() and
// cap() are built in to the compiler and have overhead more like
// variable access than function call.
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
// slices can be resliced, as long as there is space
// in the underlying array.
s = s[:5]
fmt.Println("s =", s)
// s still based on a
a[0] = 22
fmt.Println("a =", a)
fmt.Println("s =", s)
// append will automatically allocate a larger underlying array as needed.
s = append(s, 4, 5, 6)
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
// s no longer based on a
a[4] = -1
fmt.Println("a =", a)
fmt.Println("s =", s)
// make creates a slice and allocates a new underlying array
s = make([]int, 8)
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
// the cap()=10 array is no longer referenced
// and would be garbage collected eventually.
}
Output:
len(a) = 5
a = [0 0 0 0 0]
a = [3 0 0 0 0]
a[0] = 3
s = [3 0 0 0]
len(s) = 4 cap(s) = 5
s = [3 0 0 0 0]
a = [22 0 0 0 0]
s = [22 0 0 0 0]
s = [22 0 0 0 0 4 5 6]
len(s) = 8 cap(s) = 10
a = [22 0 0 0 -1]
s = [22 0 0 0 0 4 5 6]
s = [0 0 0 0 0 0 0 0]
len(s) = 8 cap(s) = 8
## Golfscript
In Golfscript, arrays are created writing their elements between []. Arrays can contain any kind of object. Once created, they are pushed on the stack, as any other object.
[1 2 3]:a; # numeric only array, assigned to a and then dropped
10,:a; # assign to a [0 1 2 3 4 5 6 7 8 9]
a 0= puts # pick element at index 0 (stack: 0)
a 10+puts # append 10 to the end of a
10 a+puts # prepend 10 to a
Append and prepend works for integers or arrays only, since only in these cases the result is coerced to an array.
## Groovy
Arrays and lists are synonymous in Groovy. They can be initialized with a wide range of operations and Groovy enhancements to the Collection and List classes.
def aa = [ 1, 25, 31, -3 ] // list
def a = [0] * 100 // list of 100 zeroes
def b = 1..9 // range notation
def c = (1..10).collect { 2.0**it } // each output element is 2**(corresponding invoking list element)
// There are no true "multi-dimensional" arrays in Groovy (as in most C-derived languages).
// Use lists of lists in natural ("row major") order as a stand in.
def d = (0..1).collect { i -> (1..5).collect { j -> 2**(5*i+j) as double } }
def e = [ [ 1.0, 2.0, 3.0, 4.0 ],
[ 5.0, 6.0, 7.0, 8.0 ],
[ 9.0, 10.0, 11.0, 12.0 ],
[ 13.0, 14.0, 15.0, 16.0 ] ]
println aa
println b
println c
println()
d.each { print "["; it.each { elt -> printf "%7.1f ", elt }; println "]" }
println()
e.each { print "["; it.each { elt -> printf "%7.1f ", elt }; println "]" }
Output:
[1, 25, 31, -3]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
[ 2.0 4.0 8.0 16.0 32.0 ]
[ 64.0 128.0 256.0 512.0 1024.0 ]
[ 1.0 2.0 3.0 4.0 ]
[ 5.0 6.0 7.0 8.0 ]
[ 9.0 10.0 11.0 12.0 ]
[ 13.0 14.0 15.0 16.0 ]
Here is a more interesting example showing a function that creates and returns a square identity matrix of order N:
def identity = { n ->
(1..n).collect { i -> (1..n).collect { j -> i==j ? 1.0 : 0.0 } }
}
Test program:
def i2 = identity(2)
def i15 = identity(15)
i2.each { print "["; it.each { elt -> printf "%4.1f ", elt }; println "]" }
println()
i15.each { print "["; it.each { elt -> printf "%4.1f ", elt }; println "]" }
Output:
[ 1.0 0.0 ]
[ 0.0 1.0 ]
[ 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ]
[ 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ]
[ 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ]
[ 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ]
[ 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ]
[ 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ]
[ 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ]
[ 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ]
[ 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 ]
[ 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 ]
[ 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 ]
[ 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 ]
[ 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 ]
[ 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 ]
[ 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 ]
Groovy, like every other C-derived language in the known universe, uses ZERO-based array/list indexing.
def strings = ['Mary', 'had', 'a', 'little', 'lamb', ". It's", 'fleece', 'was', 'white', 'as', 'snow']
println strings
strings[0] = 'Arthur'
strings[4] = 'towel'
strings[6] = 'stain'
strings[8] = 'ripe'
strings[10] = 'strawberries'
println strings
Output:
["Mary", "had", "a", "little", "lamb", ". It's", "fleece", "was", "white", "as", "snow"]
["Arthur", "had", "a", "little", "towel", ". It's", "stain", "was", "ripe", "as", "strawberries"]
Negative indices are valid. They indicate indexing from the end of the list towards the start.
println strings[-1]
Output:
strawberries
Groovy lists can be resequenced and subsequenced by providing lists or ranges of indices in place of a single index.
println strings[0, 7, 2, 3, 8]
println strings[0..4]
println strings[0..3, -5]
Output:
["Arthur", "was", "a", "little", "ripe"]
["Arthur", "had", "a", "little", "towel"]
["Arthur", "had", "a", "little", "stain"]
## GUISS
Graphical User Interface Support Script does not have variables or array storage of its own. However, it can make use of installed applications, so it is possible to utilize an installed spreadsheet application to create and manipulate arrays. Here we assume that a spreadsheet is installed and create an array containing three names:
Start,Programs,Lotus 123,Type:Bob[downarrow],Kat[downarrow],Sarah[downarrow]
## GW-BASIC
"An array, once dimensioned, cannot be re-dimensioned within the program without first executing a CLEAR or ERASE statement." (GW-BASIC User's Guide)
10 DATA 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
20 DIM A(9) ' Array with size 10 (9 is maximum subscript), all elements are set to 0
30 FOR I = 0 TO 9
40 READ A(I) ' Initialize by reading data
50 NEXT I
60 PRINT A(4) ' Get 4th element of array
70 A(4) = 400 ' Set 4th element of array
80 PRINT A(4)
## Harbour
Harbour arrays aren't divided to fixed-length and dynamic. Even if we declare it with a certain dimensions, it can be resized in the same way as it was created dynamically. The first position in an array is 1, not 0, as in some other languages.
// Declare and initialize two-dimensional array
local arr1 := { { "NITEM", "N", 10, 0 }, { "CONTENT", "C", 60, 0 } }
// Create an empty array
local arr2 := {}
// Declare three-dimensional array
local arr3[ 2, 100, 3 ]
// Create an array
local arr4 := Array( 50 )
// Array can be dynamically resized:
arr4 := ASize( arr4, 80 )
Items, including nested arrays, can be added to existing array, deleted from it, assigned to it
// Adding new item to array, its size is incremented
AAdd( arr1, { "LBASE", "L", 1, 0 } )
// Delete the first item of arr3, The size of arr3 remains the same, all items are shifted to one position, the last item is replaced by Nil:
ADel( arr1, 1 )
// Assigning a value to array item
arr3[ 1, 1, 1 ] := 11.4
Retrieve items of an array:
x := arr3[ 1, 10, 2 ]
// The retrieved item can be nested array, in this case it isn't copied, the pointer to it is assigned
There is a set of functions to manage arrays in Clipper, including the following:
// Fill the 20 items of array with 0, starting from 5-th item:
AFill( arr4, 0, 5, 20 )
// Copy 10 items from arr4 to arr3[ 2 ], starting from the first position:
ACopy( arr4, arr3[ 2 ], 1, 10 )
// Duplicate the whole or nested array:
arr5 := AClone( arr1 )
arr6 := AClone( arr1[ 3 ] )
You can read all about Haskell arrays here. The following example is taken from that page:
import Data.Array.IO
main = do arr <- newArray (1,10) 37 :: IO (IOArray Int Int)
a <- readArray arr 1
writeArray arr 1 64
b <- readArray arr 1
print (a,b)
## HicEst
REAL :: n = 3, Astat(n), Bdyn(1, 1)
Astat(2) = 2.22222222
WRITE(Messagebox, Name) Astat(2)
ALLOCATE(Bdyn, 2*n, 3*n)
Bdyn(n-1, n) = -123
WRITE(Row=27) Bdyn(n-1, n)
ALIAS(Astat, n-1, last2ofAstat, 2)
WRITE(ClipBoard) last2ofAstat ! 2.22222222 0
## I
software {
var a = []
a += 2
print(a[0]) //Outputs 2
a[0] = 4
print(a[0]) //Outputs 4
}
## Icon and Unicon
### Icon
record aThing(a, b, c) # arbitrary object (record or class) for illustration
procedure main()
A0 := [] # empty list
A0 := list() # empty list (default size 0)
A0 := list(0) # empty list (literal size 0)
A1 := list(10) # 10 elements, default initializer &null
A2 := list(10, 1) # 10 elements, initialized to 1
# literal array construction - arbitrary dynamically typed members
A3 := [1, 2, 3, ["foo", "bar", "baz"], aThing(1, 2, 3), "the end"]
# left-end workers
# NOTE: get() is a synonym for pop() which allows nicely-worded use of put() and get() to implement queues
#
Q := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x := pop(A0) # x is 1
x := get(A0) # x is 2
push(Q,0)
# Q is now [0,3, 4, 5, 6, 7, 8, 9, 10]
# right-end workers
x := pull(Q) # x is 10
put(Q, 100) # Q is now [0, 3, 4, 5, 6, 7, 8, 9, 100]
# push and put return the list they are building
# they also can have multiple arguments which work like repeated calls
Q2 := put([],1,2,3) # Q2 is [1,2,3]
Q3 := push([],1,2,3) # Q3 is [3,2,1]
Q4 := push(put(Q2),4),0] # Q4 is [0,1,2,3,4] and so is Q2
# array access follows with A as the sample array
A := [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
# get element indexed from left
x := A[1] # x is 10
x := A[2] # x is 20
x := A[10] # x is 100
# get element indexed from right
x := A[-1] # x is 100
x := A[-2] # x is 90
x := A[-10] # x is 10
# copy array to show assignment to elements
B := copy(A)
# assign element indexed from left
B[1] := 11
B[2] := 21
B[10] := 101
# B is now [11, 21, 30, 50, 60, 60, 70, 80, 90, 101]
# assign element indexed from right - see below
B[-1] := 102
B[-2] := 92
B[-10] := 12
# B is now [12, 21, 30, 50, 60, 60, 70, 80, 92, 102]
# list slicing
# the unusual nature of the slice - returning 1 less element than might be expected
# in many languages - is best understood if you imagine indexes as pointing to BEFORE
# the item of interest. When a slice is made, the elements between the two points are
# collected. eg in the A[3 : 6] sample, it will get the elements between the [ ] marks
#
# sample list: 10 20 [30 40 50] 60 70 80 90 100
# positive indexes: 1 2 3 4 5 6 7 8 9 10 11
# non-positive indexes: -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
#
# I have deliberately drawn the indexes between the positions of the values.
# The nature of this indexing brings simplicity to string operations
#
# list slicing can also use non-positive indexes to access values from the right.
# The final index of 0 shown above shows how the end of the list can be nominated
# without having to know it's length
#
# NOTE: list slices are distinct lists, so assigning to the slice
# or a member of the slice does not change the values in A
#
# Another key fact to understand: once the non-positive indexes and length-offsets are
# resolved to a simple positive index, the index pair (if two are given) are swapped
# if necessary to yield the elements between the two.
#
S := A[3 : 6] # S is [30, 40, 50]
S := A[6 : 3] # S is [30, 40, 50] not illegal or erroneous
S := A[-5 : -8] # S is [30, 40, 50]
S := A[-8 : -5] # S is [30, 40, 50] also legal and meaningful
# list slicing with length request
S := A[3 +: 3] # S is [30, 40, 50]
S := A[6 -: 3] # S is [30, 40, 50]
S := A[-8 +: 3] # S is [30, 40, 50]
S := A[-5 -: 3] # S is [30, 40, 50]
S := A[-8 -: -3] # S is [30, 40, 50]
S := A[-5 +: -3] # S is [30, 40, 50]
end
### Unicon
This Icon solution works in Unicon.
# Unicon provides a number of extensions
# insert and delete work on lists allowing changes in the middle
# possibly others
This example is in need of improvement: Need code examples for these extensions
## Io
foo := list("foo", "bar", "baz")
foo at(1) println // bar
foo append("Foobarbaz")
foo println
foo atPut(2, "barbaz") // baz becomes barbaz
Io> foo := list("foo", "bar", "baz")
==> list(foo, bar, baz)
Io> foo at(1) println // bar
bar
==> bar
Io> foo append("Foobarbaz")
==> list(foo, bar, baz, Foobarbaz)
Io> foo println
list(foo, bar, baz, Foobarbaz)
==> list(foo, bar, baz, Foobarbaz)
Io> foo atPut(2, "barbaz") // baz becomes barbaz
==> list(foo, bar, barbaz, Foobarbaz)
Io>
## J
In J, all data occurs in the form of rectangular (or generally orthotopic) arrays. This is true for both named and anonymous data.
1 NB. a stand-alone scalar value is an array without any axis
1
NB. invoking any array produces that array as the result
{. array=: 1 3, 6#0 NB. create, name, then get head item of the array: 1 3 0 0 0 0 0 0
1
0 { array NB. another way to get the head item
1
aword=: 'there' NB. a literal array
0 1 3 2 2 { aword NB. multiple items can be drawn in a single action
three
]twoD=: 3 5 \$ 'abcdefghijklmnopqrstuvwxyz'
abcde
fghij
klmno
1 { twoD NB. item 1 from twoD - a list of three items
fghij
1 {"1 twoD NB. item 1 from each rank-1 item of twoD (i.e. column 1)
bgl
(<2 2){ twoD NB. bracket indexing is not used in J
m
'X' 1} aword NB. amend item 1
tXere
aword=: 'X' 1 4} aword NB. in-place amend of items 1 and 4
tXerX
'X' (0 0;1 1;2 2)} twoD NB. amend specified items
Xbcde
fXhij
klXno
Because arrays are so important in J, a large portion of the language applies to this topic.
## Java
int[] array = new int[10]; //optionally, replace "new int[10]" with a braced list of ints like "{1, 2, 3}"
array[0] = 42;
System.out.println(array[3]);
Dynamic arrays can be made using Lists. Leave generics out for Java versions under 1.5:
ArrayList <Integer> list = new ArrayList <Integer>();//optionally add an initial size as an argument
list.add(5);//appends to the end of the list
list.add(1, 6);//assigns the element at index 1
System.out.println(list.get(0));
## JavaScript
JavaScript arrays are Objects that inherit from Array prototype and have a special length property that is always one higher than the highest non–negative integer index. Methods inherited from Array.prototype are mostly generic and can be applied to other objects with a suitable length property and numeric property names. Note that if the Array constructor is provided with one argument, it is treated as specifying the length of the new array, if more than one argument is supplied, they are treated as members of the new array.
// Create a new array with length 0
var myArray = new Array();
// Create a new array with length 5
var myArray1 = new Array(5);
// Create an array with 2 members (length is 2)
var myArray2 = new Array("Item1","Item2");
// Create an array with 2 members using an array literal
var myArray3 = ["Item1", "Item2"];
// Assign a value to member [2] (length is now 3)
myArray3[2] = 5;
var x = myArray[2] + myArray.length; // 8
// You can also add a member to an array with the push function (length is now 4)
myArray3.push('Test');
// Elisions are supported, but are buggy in some implementations
var y = [0,1,,]; // length 3, or 4 in buggy implementations
## jq
jq arrays have the same syntax as JSON arrays, and there are similarities with Javascript arrays. For example, the index origin is 0; and if a is an array and if n is an integer less than the array's length, then a[n] is the n-th element. The length of any array, a, can be ascertained using the length filter: a|length.
There are, however, some interesting extensions, e.g. [][4] = null creates an array of length 5 as explained below.
# Create a new array with length 0
[]
# Create a new array of 5 nulls
[][4] = null # setting the element at offset 4 expands the array
# Create an array having the elements 1 and 2 in that order
[1,2]
# Create an array of integers from 0 to 10 inclusive
[ range(0; 11) ]
# If a is an array (of any length), update it so that a[2] is 5
a[2] = 5;
# Append arrays a and b
a + b
# Append an element, e, to an array a
a + [e]
##################################################
# In the following, a is assumed to be [0,1,2,3,4]
# It is not an error to use an out-of-range index:
a[10] # => null
# Negative indices count backwards from after the last element:
a[-1] # => 4
# jq supports simple slice operations but
# only in the forward direction:
a[:1] # => [0]
a[1:] # => [1,2,3,4]
a[2:4] # => [2,3]
a[4:2] # null
## Julia
Julia has both heterogeneous arrays and typed arrays.
julia> A = cell(3) # create an heterogeneous array of length 3
3-element Array{Any,1}:
#undef
#undef
#undef
julia> A[1] = 4.5 ; A[3] = "some string" ; show(A)
{4.5,#undef,"some string"}
julia> A[1] # access a value. Arrays are 1-indexed
4.5
julia> push!(A, :symbol) ; show(A) # append an element
{4.5,#undef,"some string",:symbol}
julia> A[10] # error if the index is out of range
ERROR: BoundsError()
For typed arrays, the type can be specified explicitely or infered from its elements.
julia> B = Array(String, 3) ; B[1]="first" ; push!(B, "fourth") ; show(B)
["first",#undef,#undef,"fourth"]
julia> push!(B, 3) # type error
ERROR: no method convert(Type{String}, Int64)
in push! at array.jl:488
julia> ['a':'c'] # type inference
3-element Array{Char,1}:
'a'
'b'
'c'
## KonsolScript
//creates an array of length 3
Array:New array[3]:Number;
function main() {
Var:Number length;
Array:GetLength(array, length) //retrieve length of array
Konsol:Log(length)
array[0] = 5; //assign value
Konsol:Log(array[0]) //retrieve value and display
}
## Kotlin
fun main(x: Array<String>) {
var a = arrayOf(1, 2, 3, 4)
println(a.asList())
a += 5
println(a.asList())
println(a.reversedArray().asList())
}
Output:
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
## LabVIEW
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
## lang5
[]
1 append
['foo 'bar] append
2 reshape
0 remove 2 swap 2 compress collapse .
## Lasso
Lasso Array [1] objects store zero or more elements and provide random access to those elements by position. Positions are 1-based integers. Lasso Arrays will grow as needed to accommodate new elements. Elements can be inserted and removed from arrays at any position. However, inserting an element anywhere but at the end of an array results in all subsequent elements being moved down.
// Create a new empty array
local(array1) = array
// Create an array with 2 members (#myarray->size is 2)
local(array1) = array('ItemA','ItemB')
// Assign a value to member [2]
#array1->get(2) = 5
// Retrieve a value from an array
#array1->get(2) + #array1->size // 8
// Merge arrays
local(
array1 = array('a','b','c'),
array2 = array('a','b','c')
)
#array1->merge(#array2) // a, b, c, a, b, c
// Sort an array
#array1->sort // a, a, b, b, c, c
// Remove value by index
#array1->remove(2) // a, b, b, c, c
// Remove matching items
#array1->removeall('b') // a, c, c
// Insert item
#array1->insert('z') // a, c, c, z
// Insert item at specific position
#array1->insert('0',1) // 0, a, c, c, z
### Static Arrays
Lasso also supports Static Arrays[2]. A Lasso staticarray is a container object that is not resizable. Staticarrays are created with a fixed size. Objects can be reassigned within the staticarray, but new positions cannot be added or removed.
// Create a staticarray containing 5 items
local(mystaticArray) = staticarray('a','b','c','d','e')
// Retreive an item
#mystaticArray->get(3) // c
// Set an item
#mystaticArray->get(3) = 'changed' // a, b, changed, d, e
// Create an empty static array with a length of 32
local(mystaticArray) = staticarray_join(32,void)
## LFE
Using the LFE REPL, you can explore arrays in the following manner:
; Create a fixed-size array with entries 0-9 set to 'undefined'
> (set a0 (: array new 10))
#(array 10 0 undefined 10)
> (: array size a0)
10
; Create an extendible array and set entry 17 to 'true',
; causing the array to grow automatically
> (set a1 (: array set 17 'true (: array new)))
#(array
18
...
(: array size a1)
18
; Read back a stored value
> (: array get 17 a1)
true
; Accessing an unset entry returns the default value
> (: array get 3 a1)
undefined
; Accessing an entry beyond the last set entry also returns the
; default value, if the array does not have fixed size
> (: array get 18 a1)
undefined
; "sparse" functions ignore default-valued entries
> (set a2 (: array set 4 'false a1))
#(array
18
...
> (: array sparse_to_orddict a2)
(#(4 false) #(17 true))
; An extendible array can be made fixed-size later
> (set a3 (: array fix a2))
#(array
18
...
; A fixed-size array does not grow automatically and does not
; allow accesses beyond the last set entry
> (: array set 18 'true a3)
in (array set 3)
> (: array get 18 a3)
in (array get 2)
## Liberty BASIC
Arrays of less than 10 terms need not be dimensioned.
Arrays may only be 1D or 2D.
An empty numeric array term returns '0'. Empty string array terms ="".
'redim'ming allows the array size to be extended, but all existing values are lost.
DATA is READ into variables. It cannot be READ directly into arrays.
To fill arrays with DATA items, first READ the item into a variable, then use that variable to fill an index of the array.
dim Array(10)
Array(0) = -1
Array(10) = 1
print Array( 0), Array( 10)
REDIM Array( 100)
print Array( 0), Array( 10)
Array( 0) = -1
print Array( 0), Array( 10)
## Lingo
a = [1,2] -- or: a = list(1,2)
put a[2] -- or: put a.getAt(2)
-- 2
a.append(3)
put a
-- [1, 2, 3]
a.deleteAt(2)
put a
-- [1, 3]
a[1] = 5 -- or: a.setAt(1, 5)
put a
-- [5, 3]
a.sort()
put a
-- [3, 5]
In addition to the 'list' type shown above, for arrays of bytes (i.e. integers between 0 and 255) there is also the bytearray data type:
ba = bytearray(2, 255) -- initialized with size 2 and filled with 0xff
put ba
-- <ByteArrayObject length = 2 ByteArray = 0xff, 0xff >
ba[1] = 1
ba[2] = 2
ba[ba.length+1] = 3 -- dynamically increases size
put ba
-- <ByteArrayObject length = 3 ByteArray = 0x1, 0x2, 0x3 >
ba[1] = 5
put ba
-- <ByteArrayObject length = 3 ByteArray = 0x5, 0x2, 0x3 >
## Lisaac
+ a : ARRAY(INTEGER);
a := ARRAY(INTEGER).create 0 to 9;
a.put 1 to 0;
a.put 3 to 1;
a.item(1).print;
## Little
Arrays in Little are list of values of the same type and they grow dynamically.
String fruit[] = {"apple", "orange", "Pear"}
They are zero-indexed. You can use END to get the last element of an array:
puts(fruit[0]);
puts(fruit[1]);
puts(fruit[END]);
fruit[END+1] = "banana";
## Logo
array 5 ; default origin is 1, every item is empty
(array 5 0) ; custom origin
make "a {1 2 3 4 5} ; array literal
setitem 1 :a "ten ; Logo is dynamic; arrays can contain different types
print item 1 :a ; ten
## LSE64
10 myArray :array
0 array 5 [] ! # store 0 at the sixth cell in the array
array 5 [] @ # contents of sixth cell in array
## LSL
LSL does not have Arrays, but it does have lists which can function similar to a one dimensional ArrayList in Java or C#.
default {
state_entry() {
list lst = ["1", "2", "3"];
llSay(0, "Create and Initialize a List\nList=["+llList2CSV(lst)+"]\n");
lst += ["A", "B", "C"];
llSay(0, "Append to List\nList=["+llList2CSV(lst)+"]\n");
lst = llListInsertList(lst, ["4", "5", "6"], 3);
llSay(0, "List Insertion\nList=["+llList2CSV(lst)+"]\n");
lst = llListReplaceList(lst, ["a", "b", "c"], 3, 5);
llSay(0, "Replace a portion of a list\nList=["+llList2CSV(lst)+"]\n");
lst = llListRandomize(lst, 1);
llSay(0, "Randomize a List\nList=["+llList2CSV(lst)+"]\n");
lst = llListSort(lst, 1, TRUE);
llSay(0, "Sort a List\nList=["+llList2CSV(lst)+"]\n");
lst = [1, 2.0, "string", (key)NULL_KEY, ZERO_VECTOR, ZERO_ROTATION];
string sCSV = llList2CSV(lst);
llSay(0, "Serialize a List of different datatypes to a string\n(integer, float, string, key, vector, rotation)\nCSV=\""+sCSV+"\"\n");
lst = llCSV2List(sCSV);
llSay(0, "Deserialize a string CSV List\n(note that all elements are now string datatype)\nList=["+llList2CSV(lst)+"]\n");
}
}
Output:
Create and Initialize a List
List=[1, 2, 3]
Append to List
List=[1, 2, 3, A, B, C]
List Insertion
List=[1, 2, 3, 4, 5, 6, A, B, C]
Replace a portion of a list
List=[1, 2, 3, a, b, c, A, B, C]
Randomize a List
List=[2, 3, B, a, A, b, C, c, 1]
Sort a List
List=[1, 2, 3, a, A, b, B, c, C]
Serialize a List of different datatypes to a string
(integer, float, string, key, vector, rotation)
CSV="1, 2.000000, string, 00000000-0000-0000-0000-000000000000, <0.00000, 0.00000, 0.00000>, <0.00000, 0.00000, 0.00000, 1.00000>"
Deserialize a string CSV List
(note that all elements are now string datatype)
List=[1, 2.000000, string, 00000000-0000-0000-0000-000000000000, <0.00000, 0.00000, 0.00000>, <0.00000, 0.00000, 0.00000, 1.00000>]
## Lua
Lua does not differentiate between arrays, lists, sets, dictionaries, maps, etc. It supports only one container: Table. Using Lua's simple yet powerful syntax, any of these containers can be emulated. All tables are dynamic. If a static array is necessary, that behavior can be created.
l = {}
l[1] = 1 -- Index starts with 1, not 0.
l[0] = 'zero' -- But you can use 0 if you want
l[10] = 2 -- Indexes need not be continuous
l.a = 3 -- Treated as l['a']. Any object can be used as index
l[l] = l -- Again, any object can be used as an index. Even other tables
for i,v in next,l do print (i,v) end
## Maple
#defining an array of a certain length
a := Array (1..5);
a := [ 0 0 0 0 0 ]
#can also define with a list of entries
a := Array ([1, 2, 3, 4, 5]);
a := [ 1 2 3 4 5 ]
a[1] := 9;
a
a[1] := 9
[ 9 2 3 4 5 ]
a[5];
5
#can only grow arrays using ()
a(6) := 6;
a := [ 9 2 3 4 5 6 ]
a[7] := 7;
Error, Array index out of range
## Mathematica / Wolfram Language
a = Array[Sin, 10]
a[[1]]
Delete[a, 2]
Output:
{Sin[1],Sin[2],Sin[3],Sin[4],Sin[5],Sin[6],Sin[7],Sin[8],Sin[9],Sin[10]}
Sin[1]
{Sin[1],Sin[3],Sin[4],Sin[5],Sin[6],Sin[7],Sin[8],Sin[9],Sin[10]}
## MATLAB / Octave
Variables are not typed until they are initialized. So, if you want to create an array you simply assign a variable name the value of an array. Also, memory is managed by MATLAB so an array can be expanded, resized, and have elements deleted without the user dealing with memory. Array elements can be retrieved in two ways. The first way is to input the row and column indicies of the desired elements. The second way is to input the subscript of the array elements.
>> a = [1 2 35] %Declaring a vector (i.e. one-dimensional array)
a =
1 2 35
>> a = [1 2 35;5 7 9] % Declaring a matrix (i.e. two-dimensional array)
a =
1 2 35
5 7 9
>> a3 = reshape(1:2*3*4,[2,3,4]); % declaring a three-dimensional array of size 2x3x4
a3 =
ans(:,:,1) =
1 3 5
2 4 6
ans(:,:,2) =
7 9 11
8 10 12
ans(:,:,3) =
13 15 17
14 16 18
ans(:,:,4) =
19 21 23
20 22 24
>> a(2,3) %Retrieving value using row and column indicies
9
>> a(6) %Retrieving value using array subscript
ans =
9
>> a = [a [10;42]] %Added a column vector to the array
a =
1 2 35 10
5 7 9 42
>> a(:,1) = [] %Deleting array elements
a =
2 35 10
7 9 42
## Maxima
/* Declare an array, subscripts run from 0 to max value */
array(a, flonum, 20, 20, 3)\$
arrayinfo(a);
/* [complete, 3, [20, 20, 3]] */
a[0, 0]: 1.0;
listarray(a);
/* [1.0, 0.0, 0.0, ..., 0.0] */
/* Show all declared arrays */
arrays;
/* [a] */
/* One may also use an array without declaring it, it's a hashed array */
b[1]: 1000;
b['x]: 3/4; /* hashed array may have any subscript */
arrayinfo(b);
/* [hashed, 1, [1], [x]] */
listarray(b);
/* [1000, 3/4] */
## MIPS Assembly
.data
array: .word 1, 2, 3, 4, 5, 6, 7, 8, 9 # creates an array of 9 32 Bit words.
.text
main: la \$s0, array
li \$s1, 25
sw \$s1, 4(\$s0) # writes \$s1 (25) in the second array element
# the four counts thi bytes after the beginning of the address. 1 word = 4 bytes, so 4 acesses the second element
lw \$s2, 20(\$s0) # \$s2 now contains 6
li \$v0, 10 # end program
syscall
## Modula-3
VAR a: ARRAY [1..10] OF INTEGER;
Defines an array of 10 elements, indexed 1 through 10.
Arrays can also be given initial values:
VAR a := ARRAY [1..10] OF INTEGER {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
VAR arr1 := ARRAY [1..10] OF INTEGER {1, ..} (* Initialize all elements to 1. *)
To retrieve an element:
VAR arr := ARRAY [1..3] OF INTEGER {1, 2, 3};
VAR myVar := a[2];
To assign a value to an element:
VAR arr := ARRAY [1..3] OF INTEGER;
arr[1] := 10;
## Monte
var myArray := ['a', 'b', 'c','d']
To retrieve a value:
traceln(myArray[0])
To change a value:
myArray := myArray.with(3, 'z')
Now myArray is ['a','b','c','z'].
## Neko
var myArray = \$array(1);
\$print(myArray[0]);
Output:
1
## Nemerle
using System;
using System.Console;
using System.Collections;
module ArrayOps
{
Main() : void
{
def fives = array(10);
foreach (i in [1 .. 10]) fives[i - 1] = i * 5;
def ten = fives[1];
WriteLine(\$"Ten: \$ten");
def dynamic = ArrayList();
dynamic[1] = 2;
foreach (i in dynamic) Write(\$"\$i\t"); // Nemerle isn't great about displaying arrays, it's better with lists though
}
}
## NetRexx
Note: Dynamic arrays can be simulated via the Java Collections Framework or by using NetRexx indexed strings (AKA: associative arrays).
/* NetRexx */
options replace format comments java crossref symbols nobinary
array = int[10]
array[0] = 42
say array[0] array[3]
say
words = ['Ogof', 'Ffynnon', 'Ddu']
say words[0] words[1] words[2]
say
-- Dynamic arrays can be simulated via the Java Collections package
splk = ArrayList()
say splk.get(0) splk.get(3)
say splk.get(0) splk.get(1) splk.get(2)
say
-- or by using NetRexx "indexed strings" (associative arrays)
cymru = ''
cymru[0] = 0
cymru[0] = cymru[0] + 1; cymru[cymru[0]] = splk.get(0) splk.get(1) splk.get(2)
cymru[0] = cymru[0] + 1; cymru[cymru[0]] = splk.get(0) splk.get(3)
loop x_ = 1 to cymru[0] by 1
say x_':' cymru[x_]
end x_
Output:
42 0
Ogof Ffynnon Ddu
Ogof Draenen
Ogof Ffynnon Ddu
1: Ogof Ffynnon Ddu
2: Ogof Draenen
## NewLISP
This creates an array of 5 elements, initialized to nil:
(array 5)
(nil nil nil nil nil)
The example below creates a multi-dimensional array (a 3-element array of 4-element arrays), initialized using the values returned by the function sequence (a list containing whole numbers from 1 to 12) and stores the newly created array in a variable called myarray. The return value of the set function is the array.
(set 'myarray (array 3 4 (sequence 1 12)))
((1 2 3 4) (5 6 7 8) (9 10 11 12))
## Nim
var # fixed size arrays
x = [1,2,3,4,5,6,7,8,9,10] # type and size automatically inferred
y: array[1..5, int] = [1,2,3,4,5] # starts at 1 instead of 0
z: array['a'..'z', int] # indexed using characters
x[0] = x[1] + 1
echo x[0]
echo z['d']
x[7..9] = y[3..5] # copy part of array
var # variable size sequences
a = @[1,2,3,4,5,6,7,8,9,10]
b: seq[int] = @[1,2,3,4,5]
a[0] = a[1] + 1
echo a[0]
a.add(b) # append another sequence
a.add(200) # append another element
echo a.pop() # pop last item, removing and returning it
echo a
## NSIS
Library: NSISArray
NSIS does not have native support for arrays. Array support is provided by the NSISArray plugin.
!include NSISArray.nsh
Function ArrayTest
Push \$0
; Declaring an array
NSISArray::New TestArray 1 2
NSISArray::Push TestArray "Hello"
; NSISArray arrays are dynamic by default.
NSISArray::Push TestArray "World"
Pop \$0
DetailPrint \$0
Pop \$0
FunctionEnd
## Oberon-2
MODULE Arrays;
IMPORT
Out;
PROCEDURE Static;
VAR
x: ARRAY 5 OF LONGINT;
BEGIN
x[0] := 10;
x[1] := 11;
x[2] := 12;
x[3] := 13;
x[4] := x[0];
Out.String("Static at 4: ");Out.LongInt(x[4],0);Out.Ln;
END Static;
PROCEDURE Dynamic;
VAR
x: POINTER TO ARRAY OF LONGINT;
BEGIN
NEW(x,5);
x[0] := 10;
x[1] := 11;
x[2] := 12;
x[3] := 13;
x[4] := x[0];
Out.String("Dynamic at 4: ");Out.LongInt(x[4],0);Out.Ln;
END Dynamic;
BEGIN
Static;
Dynamic
END Arrays.
## Objeck
bundle Default {
class Arithmetic {
function : Main(args : System.String[]), Nil {
array := Int->New[2];
array[0] := 13;
array[1] := 7;
(array[0] + array[1])->PrintLine();
}
}
}
## Objective-C
// NSArrays are ordered collections of NSObject subclasses only.
// Create an array of NSString objects.
NSArray *firstArray = [[NSArray alloc] initWithObjects:@"Hewey", @"Louie", @"Dewey", nil];
// NSArrays are immutable; it does have a mutable subclass, however - NSMutableArray.
// Let's instantiate one with a mutable copy of our array.
// We can do this by sending our first array a -mutableCopy message.
NSMutableArray *secondArray = [firstArray mutableCopy];
// Replace Louie with Launchpad McQuack.
// Display the first object in the array.
NSLog(@"%@", [secondArray objectAtIndex:0]);
// In non-ARC or non-GC environments, retained objects must be released later.
[firstArray release];
[secondArray release];
// There is also a modern syntax which allows convenient creation of autoreleased immutable arrays.
// No nil termination is then needed.
NSArray *thirdArray = @[ @"Hewey", @"Louie", @"Dewey", @1, @2, @3 ];
## OCaml
in the toplevel:
# Array.make 6 'A' ;;
- : char array = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|]
# Array.init 8 (fun i -> i * 10) ;;
- : int array = [|0; 10; 20; 30; 40; 50; 60; 70|]
# let arr = [|0; 1; 2; 3; 4; 5; 6 |] ;;
val arr : int array = [|0; 1; 2; 3; 4; 5; 6|]
# arr.(4) ;;
- : int = 4
# arr.(4) <- 65 ;;
- : unit = ()
# arr ;;
- : int array = [|0; 1; 2; 3; 65; 5; 6|]
## Oforth
Oforth has no Array class. Lists are immutables and can act like arrays. To have a mutable array, a ListBuffer can be used.
[ "abd", "def", "ghi" ] at(3) println
ListBuffer new dup addAll([1, 2, 3]) dup put(2, 8.1) println
Output:
ghi
[1, 8.1, 3]
## ooRexx
ooRexx arrays hold object references. Arrays will automatically increase in size if needed.
a = .array~new -- create a zero element array
b = .array~new(10) -- create an array with initial size of 10
c = .array~of(1, 2, 3) -- creates a 3 element array holding objects 1, 2, and 3
a[3] = "Fred" -- assign an item
b[2] = a[3] -- retrieve an item from the array
c~append(4) -- adds to end. c[4] == 4 now
The above Array class supports only one-dimensional arrays (vectors) with positive integer indexes. Much more powerful are stems such as a.i.j where i and j can be any string value. See category REXX for details. ooRexx introduces a notation a.[x,y] where x and y can actually be expressions. This way one can implement one- and multidimensional (associative) arrays. The indexes can be strings containing any characters including blanks. The total length of the stemmed variable (stem and index values separated by periods) must not be longer than 250.
## OxygenBasic
'CREATING AN ARRAY
float f[100]
'SETTING INDEX BASE
indexbase 1 'default
'FILLING PART OF AN ARRAY
f[20]<=1,2,3,4,5,1.25
'MAPPING AN ARRAY TO ANOTHER
float *g
@[email protected][20]
print g[6] 'result 1.25
## Oz
declare
Arr = {Array.new 1 %% lowest index
10 %% highest index
37} %% all 10 fields initialized to 37
in
{Show Arr.1}
Arr.1 := 64
{Show Arr.1}
v=[];
v=concat(v,7);
v[1]
## Pascal
A modification of the Delphi example:
Program ArrayDemo;
uses
SysUtils;
var
StaticArray: array[0..9] of Integer;
DynamicArray: array of Integer;
StaticArrayText,
DynamicArrayText: string;
lcv: Integer;
begin
// Setting the length of the dynamic array the same as the static one
SetLength(DynamicArray, Length(StaticArray));
// Asking random numbers storing into the static array
for lcv := 0 to Pred(Length(StaticArray)) do
begin
write('Enter a integer random number for position ', Succ(lcv), ': ');
end;
// Storing entered numbers of the static array in reverse order into the dynamic
for lcv := 0 to Pred(Length(StaticArray)) do
DynamicArray[Pred(Length(DynamicArray)) - lcv] := StaticArray[lcv];
// Concatenating the static and dynamic array into a single string variable
StaticArrayText := '';
DynamicArrayText := '';
for lcv := 0 to Pred(Length(StaticArray)) do
begin
StaticArrayText := StaticArrayText + IntToStr(StaticArray[lcv]) + ' ';
DynamicArrayText := DynamicArrayText + IntToStr(DynamicArray[lcv]) + ' ';
end;
// Displaying both arrays
writeln(StaticArrayText);
writeln(DynamicArrayText);
end.
## Perl
In-line
my @empty;
my @empty_too = ();
my @populated = ('This', 'That', 'And', 'The', 'Other');
print \$populated[2]; # And
my \$aref = ['This', 'That', 'And', 'The', 'Other'];
print \$aref->[2]; # And
Dynamic
my @arr;
push @arr, 1;
push @arr, 3;
\$arr[0] = 2;
print \$arr[0];
Two-dimensional
my @multi_dimensional = (
[0, 1, 2, 3],
[qw(a b c d e f g)],
[qw(! \$ % & *)],
);
## Perl 6
Works with: Rakudo version 2015.12
my @arr;
push @arr, 1;
push @arr, 3;
@arr[0] = 2;
say @arr[0];
## Phix
In Phix, sequences are it - there are no other data structures to learn.
Arrays, multidimensional arrays, lists, stacks, queues, trees, etc. and even character strings can all be easily represented in Phix with sequences. They can grow or shrink without any need to worry about memory management issues.
-- simple one-dimensional arrays:
sequence s1 = {0.5, 1, 4.7, 9}, -- length(s1) is now 4
s2 = repeat(0,6), -- s2 is {0,0,0,0,0,0}
s3 = tagset(5) -- s3 is {1,2,3,4,5}
?s1[3] -- displays 4.7 (nb 1-based indexing)
s1[3] = 0 -- replace that 4.7
s1 &= {5,6} -- length(s1) is now 6 ({0.5,1,0,9,5,6})
s1 = s1[2..5] -- length(s1) is now 4 ({1,0,9,5})
s1[2..3] = {2,3,4} -- length(s1) is now 5 ({1,2,3,4,5})
s1 = append(s1,6) -- length(s1) is now 6 ({1,2,3,4,5,6})
s1 = prepend(s1,0) -- length(s1) is now 7 ({0,1,2,3,4,5,6})
-- negative subscripts can also be used, counting from the other end, eg
s2[-2..-1] = {-2,-1} -- s2 is now {0,0,0,0,-2,-1}
-- multi dimensional arrays:
sequence y = {{{1,1},{3,3},{5,5}},
{{0,0},{0,1},{9,1}},
{{1,7},{1,1},{2,2}}}
-- y[2][3][1] is 9
y = repeat(repeat(repeat(0,2),3),3)
-- same structure, but all 0s
-- Array of strings:
sequence s = {"Hello", "World", "Phix", "", "Last One"}
-- s[3] is "Phix"
-- s[3][2] is 'h'
-- A Structure:
sequence employee = {{"John","Smith"},
45000,
27,
185.5}
-- To simplify access to elements within a structure it is good programming style to define constants that name the various fields, eg:
constant SALARY = 2
-- Array of structures:
sequence employees = {
{{"Jane","Adams"}, 47000, 34, 135.5}, -- a[1]
{{"Bill","Jones"}, 57000, 48, 177.2}, -- a[2]
-- .... etc.
}
-- employees[2][SALARY] is 57000
-- A tree can be represented easily, for example after adding "b","c","a" to it you might have:
sequence tree = {{"b",3,2},
{"c",0,0},
{"a",0,0}}
-- ie assuming
constant ROOT=1, VALUE=1, LEFT=2, RIGHT=3 -- then
-- tree[ROOT][VALUE] is "b"
-- tree[ROOT][LEFT] is 3, and tree[3] is the "a"
-- tree[ROOT][RIGHT] is 2, and tree[2] is the "c"
-- The operations you might use to build such a tree (tests/loops/etc omitted) could be:
tree = {}
tree = append(tree,{"b",0,0})
tree = append(tree,{"c",0,0})
tree[1][RIGHT] = length(tree)
tree = append(tree,{"a",0,0})
tree[1][LEFT] = length(tree)
-- Finally, some tests (recall that we have already output a 4.7):
?s[3]
?tree
?tree[ROOT][VALUE]
employees = append(employees, employee)
?employees[3][SALARY]
?s1
?s2
Output:
4.7
"Phix"
{{"b",3,2},{"c",0,0},{"a",0,0}}
"b"
45000
{0,1,2,3,4,5,6}
{0,0,0,0,-2,-1}
## PHP
### Writing To An Array
#### Single Dimension
\$NumberArray = array(0, 1, 2, 3, 4, 5, 6);
\$LetterArray = array("a", "b", "c", "d", "e", "f");
\$simpleForm = ['apple', 'orange'];
#### Multi-Dimensional
\$MultiArray = array(
array(0, 0, 0, 0, 0, 0),
array(1, 1, 1, 1, 1, 1),
array(2, 2, 2, 2, 2, 2),
array(3, 3, 3, 3, 3, 3)
);
#### Array push
\$arr = ['apple', 'orange'];
array_push(\$arr, 'pear');
print implode(',', \$arr); // Returns apple,orange,pear
### Reading From An Array
#### Single Dimension
Read the 5th value in the array:
echo \$NumberArray[5]; // Returns 5
echo \$LetterArray[5]; // Returns f
#### Multi-Dimensional
Read the 2nd line, column 5
echo \$MultiArray[1][5]; // 2
### Print a whole array
This is useful while developing to view the contents of an array:
print_r(\$MultiArray);
Which would give us:
Array(
0 => array(
0 => 0
1 => 0
2 => 0
3 => 0
4 => 0
5 => 0
)
1 => array(
0 => 1
1 => 1
2 => 1
3 => 1
4 => 1
5 => 1
)
2 => array(
0 => 2
1 => 2
2 => 2
3 => 2
4 => 2
5 => 2
)
3 => array(
0 => 3
1 => 3
2 => 3
3 => 3
4 => 3
5 => 3
)
)
### Set custom keys for values
This example starts the indexing from 1 instead of 0
\$StartIndexAtOne = array(1 => "A", "B", "C", "D");
This example shows how you can apply any key you want
\$CustomKeyArray = array("d" => "A", "c" => "B", "b" =>"C", "a" =>"D");
To read the 3rd value of the second array:
echo \$CustomKeyArray["b"]; // Returns C
### Other Examples
Create a blank array:
\$BlankArray = array();
Set a value for the next key in the array:
\$BlankArray[] = "Not Blank Anymore";
Assign a value to a certain key:
\$AssignArray["CertainKey"] = "Value";
## PicoLisp
PicoLisp has no built-in array data type. Lists are used instead.
(setq A '((1 2 3) (a b c) ((d e) NIL 777))) # Create a 3x3 structure
(mapc println A) # Show it
Output:
(1 2 3)
(a b c)
((d e) NIL 777)
Replace 'b' with 'B' in middle row:
(set (nth A 2 2) 'B)
(mapc println A)
Output:
(1 2 3)
(a B c)
((d e) NIL 777)
Insert '1' in front of the middle row:
(push (cdr A) 1)
(mapc println A)
Output:
(1 2 3)
(1 a B c)
((d e) NIL 777)
Append '9' to the middle row:
(queue (cdr A) 9)
(mapc println A)
Output:
(1 2 3)
(1 a B c 9)
((d e) NIL 777)
## Pike
int main(){
// Initial array, few random elements.
array arr = ({3,"hi",84.2});
arr += ({"adding","to","the","array"}); // Lets add some elements.
write(arr[5] + "\n"); // And finally print element 5.
}
## PL/I
/* Example of an array having fixed dimensions */
declare A(10) float initial (1, 9, 4, 6, 7, 2, 5, 8, 3, 10);
A(6) = -45;
/* Example of an array having dynamic bounds. */
get list (N);
begin;
declare B(N) float initial (9, 4, 7, 3, 8, 11, 0, 5, 15, 6);
B(3) = -11;
end;
/* Example of a dynamic array. */
declare C(N) float controlled;
get list (N);
allocate C;
C = 0;
c(7) = 12;
## Pony
Arrays are homogenous.
var numbers = Array[I32](16) // creating array of 32-bit ints with initial allocation for 16 elements
numbers.push(10) // add value 10 to the end of array, extending the underlying memory if needed
try
let x = numbers(0) // fetch the first element of array. index starts at 0
Fact(x == 10) // try block is needed, because both lines inside it can throw exception
end
var other: Array[U64] = [10, 20, 30] // array literal
let s = other.size() // return the number of elements in array
try
Fact(s == 3) // size of array 'other' is 3
other(1) = 40 // 'other' now is [10, 40, 30]
end
## PostScript
%Declaring array
/x [0 1] def
%Assigning value to an element, PostScript arrays are 0 based.
x 0 3 put
%Print array
x pstack
[3 1]
%Get an element
x 1 get
## PowerShell
Empty array:
\$a = @()
Array initialized with only one member:
\$a = ,2
\$a = @(2) # alternative
Longer arrays can simply be created by separating the values with commas:
\$a = 1,2,3
A value can be appended to an array using the += operator:
\$a += 5
Since arrays are immutable this simply creates a new array containing one more member.
Values can be retrieved using a fairly standard indexing syntax:
\$a[1]
Similarly, those values can also be replaced:
\$a[1] = 42
The range operator .. can be used to create contiguous ranges of integers as arrays:
\$r = 1..100
Indexing for retrieval allows for arrays as well, the following shows a fairly complex example combining two ranges and an arbitrary array in the indexer:
\$r[0..9+25..27+80,85,90]
Indexing from the end of the array can be done with negative numbers:
\$r[-1] # last index
## Prolog
Works with: SWI Prolog
Prolog Terms can be abused as array structure. Using functor/3 to create arrays and arg/3 to nondestructively retrieve and set elements.
singleassignment:-
functor(Array,array,100), % create a term with 100 free Variables as arguments
% index of arguments start at 1
arg(1 ,Array,a), % put an a at position 1
arg(12,Array,b), % put an b at position 12
arg(1 ,Array,Value1), % get the value at position 1
print(Value1),nl, % will print Value1 and therefore a followed by a newline
arg(4 ,Array,Value2), % get the value at position 4 which is a free Variable
print(Value2),nl. % will print that it is a free Variable followed by a newline
To destructively set an array element, which is the "normal" way to set an element in most other programming languages, setarg/3 can be used.
destructive:-
functor(Array,array,100), % create a term with 100 free Variables as arguments
% index of arguments start at 1
setarg(1 ,Array,a), % put an a at position 1
setarg(12,Array,b), % put an b at position 12
setarg(1, Array,c), % overwrite value at position 1 with c
arg(1 ,Array,Value1), % get the value at position 1
print(Value1),nl. % will print Value1 and therefore c followed by a newline
Lists can be used as arrays.
listvariant:-
length(List,100), % create a list of length 100
nth1(1 ,List,a), % put an a at position 1 , nth1/3 uses indexing from 1, nth0/3 from 0
nth1(12,List,b), % put an b at position 3
append(List,[d],List2), % append an d at the end , List2 has 101 elements
length(Add,10), % create a new list of length 10
append(List2,Add,List3), % append 10 free variables to List2 , List3 now has 111 elements
nth1(1 ,List3,Value), % get the value at position 1
print(Value),nl. % will print out a
## PureBasic
Dim is used to create new arrays and initiate each element will be zero. An array in PureBasic can be of any types, including structured, and user defined types. Once an array is defined it can be resized with ReDim. Arrays are dynamically allocated which means than a variable or an expression can be used to size them.
;Set up an Array of 23 cells, e.g. 0-22
Dim MyArray.i(22)
MyArray(0) = 7
MyArray(1) = 11
MyArray(7) = 23
ReDim is used to 'resize' an already declared array while preserving its content. The new size can be both larger or smaller, but the number of dimension of the array can not be changed after initial creation.
;Extend the Array above to 56 items without affecting the already stored data
ReDim MyArray(55)
MyArray(22) = 7
MyArray(33) = 11
MyArray(44) = 23
;Find all 6 non-zero cells from the Array above
For i=0 To ArraySize(MyArray())
If MyArray(i)
PrintN(Str(i)+" differs from zero.")
EndIf
Next
; Now, set up a multi dimensional Array
Dim MultiArray.i(800, 600)
MultiArray(100, 200) = 640
MultiArray(130, 40) = 120
Dim MultiArray2.i(64, 128, 32)
PrintN( Str(ArraySize(MultiArray2(), 2)) ; Will tell that second dimension size is '128'
## Python
Python lists are dynamically resizeable.
array = []
array.append(1)
array.append(3)
array[0] = 2
print array[0]
A simple, single-dimensional array can also be initialized thus:
myArray = [0] * size
However this will not work as intended if one tries to generalize from the syntax:
myArray = [[0]* width] * height] # DOES NOT WORK AS INTENDED!!!
This creates a list of "height" number of references to one list object ... which is a list of width instances of the number zero. Due to the differing semantics of immutables (strings, numbers) and mutables (dictionaries, lists), a change to any one of the "rows" will affect the values in all of them. Thus we need to ensure that we initialize each row with a newly generated list.
To initialize a list of lists one could use a pair of nested list comprehensions like so:
myArray = [[0 for x in range(width)] for y in range(height)]
That is equivalent to:
myArray = list()
for x in range(height):
myArray.append([0] * width)
To retrieve an element in an array, use any of the following methods:
# Retrieve an element directly from the array.
item = array[index]
# Use the array like a stack. Note that using the pop() method removes the element.
array.pop() # Pop last item in a list
array.pop(0) # Pop first item in a list
# Using a negative element counts from the end of the list.
item = array[-1] # Retrieve last element in a list.
Python produces an IndexError when accessing elements out of range:
try:
# This will cause an exception, which will then be caught.
print array[len(array)]
except IndexError as e:
# Print the exception.
print e
## R
Dynamic
arr <- array(1)
arr <- append(arr,3)
arr[1] <- 2
print(arr[1])
## Racket
#lang racket
;; import dynamic arrays
(require data/gvector)
(define v (vector 1 2 3 4)) ; array
(vector-ref v 0) ; 1
(vector-set! v 1 4) ; 2 -> 4
(define gv (gvector 1 2 3 4)) ; dynamic array
(gvector-ref gv 0) ; 1
(gvector-add! gv 5) ; increase size
## REBOL
a: [] ; Empty.
b: ["foo"] ; Pre-initialized.
Inserting and appending.
append a ["up" "down"] ; -> ["up" "down"]
insert a [left right] ; -> [left right "up" "down"]
Getting specific values.
first a ; -> left
third a ; -> "up"
last a ; -> "down"
a/2 ; -> right (Note: REBOL is 1-based.)
Getting subsequences. REBOL allows relative motion through a block (list). The list variable returns the current position to the end of the list, you can even assign to it without destroying the list.
a ; -> [left right "up" "down"]
next a ; -> [right "up" "down"]
skip a 2 ; -> ["up" "down"]
a: next a ; -> [right "up" "down"]
head a ; -> [left right "up" "down"]
copy a ; -> [left right "up" "down"]
copy/part a 2 ; -> [left right]
copy/part skip a 2 2 ; -> ["up" "down"]
## Retro
Retro has a vocabulary for creating and working with arrays.
needs array'
( Create an array with four elements )
^array'new{ 1 2 3 4 } constant a
( Add 10 to each element in an array and update the array with the results )
a [ 10 + ] ^array'map
( Apply a quote to each element in an array; leaves the contents alone )
a [ 10 + putn cr ] ^array'apply
( Display an array )
a ^array'display
( Look for a value in an array )
3 a ^array'in?
6 a ^array'in?
( Look for a string in an array )
"hello" a ^array'stringIn?
( Reverse the order of items in an array )
a ^array'reverse
( Append two arrays and return a new one )
^array'new{ 1 2 3 } constant a
^array'new{ 4 5 6 } constant b
a b ^array'append constant c
( Create an array from the values returned by a quote )
[ 1 2 "hello" "world" ] ^array'fromQuote constant d
( Create a quote from the values in an array )
d ^array'toQuote
## REXX
Strictly speaking, REXX doesn't have arrays, but it does have something that looks, feels, and tastes like arrays;
they're called stemmed arrays.
### simple arrays
/*REXX program demonstrates a simple array usage. */
a.='not found' /*value for all a.xxx (so far).*/
do j=1 to 100 /*start at 1, define 100 elements*/
a.j=-j*1000 /*define as negative J thousand. */
end /*j*/ /*the above defines 100 elements.*/
say 'element 50 is:' a.50
say 'element 3000 is:' a.3000
/*stick a fork in it, we're done.*/
Output:
element 50 is: -50000
### simple arrays, mimic other languages
/*REXX program demonstrates array usage with mimicry. */
a. = 'not found' /*value for all a.xxx (so far). */
do j=1 to 100 /*start at 1, define 100 elements*/
a.j = -j * 100 /*define element as -J hundred. */
end /*j*/ /*the above defines 100 elements.*/
say 'element 50 is:' a(50)
say 'element 3000 is:' a(3000)
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────A subroutine────────────────────────*/
a: _a_ = arg(1); return a._a_
element 50 is: -5000
### simple arrays, assigned default
/*REXX program demonstrates array usage with mimicry. */
a. = 00 /*value for all a.xxx (so far). */
do j=1 to 100 /*start at 1, define 100 elements*/
a.j = -j * 100 /*define element as -J hundred. */
end /*j*/ /*the above defines 100 elements.*/
say 'element 50 is:' a(50)
say 'element 3000 is:' a(3000)
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────A subroutine────────────────────────*/
a: _a_ = arg(1); return a._a_
Output:
element 50 is: -5000
element 3000 is: 00
### arrays with non-unity index start
/*REXX program demonstrates array usage (with elements out-of-range).*/
array. = 'out of range' /*define ALL elements to this. */
do j=-3000 to 3000 /*start at -3k, going up to +3k.*/
array.j=j**2 /*define element as its square. */
end /*j*/ /* [↑] defines 6,001 elements. */
g=-7
say g "squared is:" array.g
say 7000 "squared is:" array.7000
/*stick a fork in it, we're done.*/
Output:
-7 squared is: 49
7000 squared is: out of range
### arrays, disjoint
/*REXX program demonstrates disjointed array usage. */
yr. = 'year not supported' /*value for all yr.xxx (so far).*/
do k=600 to 1100 /*a bunch of years prior to 1800.*/
yr.k=k "AD" /*Kth element as the year itself.*/
end /*k*/ /* [↑] defines 501 elements.*/
do j=1800 to 2100 /*start at 1800, define a bunch. */
yr.j=j 'AD' /*Jth element as the year itself.*/
end /*j*/ /* [↑] defines 301 elements.*/
year=1946
say 'DOB' year "is:" yr.year
year=1744
say 'DOB' year "is:" yr.year
/*stick a fork in it, we're done.*/
Output:
DOB 1946 is: 1946 AD
DOB 1744 is: year not supported
### sparse arrays and special indices
/*REXX program demonstrates array usage: sparse and disjointed. */
yyy = -55 /*REXX must use this mechanism···*/
a.yyy = 1e9 /*··· when assigning neg indices.*/
a.1 = 1000
a.2 = 2000.0001
a.7 = 7000
a.2012 = 'out here in left field.'
a.cat = 'civet, but not a true cat ─── belonging to the family Viverridae'
a.civet = "A.K.A.: toddycats"
/*┌────────────────────────────────────────────────────────────────────┐
│ Array elements need not be continuous (nor even defined). They │
│ can hold any manner of numbers, or strings (which can include any │
│ characters, including null or '00'x characters). │
│ │
│ Array elements need not be numeric, as the above code demonstrates.│
│ Indeed, the element "name" can be ANYTHING, even non-displayable │
│ characters. To illustrate [↓]: │
└────────────────────────────────────────────────────────────────────┘*/
stuff=')g.u.t.s( or ½ of an intestine!'
a.stuff=44
/*┌────────────────────────────────────────────────────────────────────┐
│ where the element name has special characters: blanks, and the │
│ glyph of one-half (½), as well as the symbol used in REXX to │
│ identify stemmed arrays (the period). │
└────────────────────────────────────────────────────────────────────┘*/
/*stick a fork in it, we're done.*/
## RLaB
// 1-D (row- or column-vectors)
// Static:
// row-vector
x = [1:3];
x = zeros(1,3); x[1]=1; x[2]=2; x[3]=3;
// column-vector
x = [1:3]'; // or
x = [1;2;3]; // or
x = zeros(3,1); x[1]=1; x[2]=2; x[3]=3;
// Dynamic:
x = []; // create an empty array
x = [x; 1, 2]; // add a row to 'x' containing [1, 2], or
x = [x, [1; 2]]; // add a column to 'x' containing [1; 2]
// 2-D array
// Static:
x = zeros(3,5); // create an zero-filed matrix of size 3x5
x[1;1] = 1; // set the x(1,1) element to 1
x[2;] = [1,2,3,4,5]; // set the second row x(2,) to a row vector
x[3;4:5] = [2,3]; // set x(3,4) to 2 and x(3,5) to 3
// Dynamic
x = [1:5]; // create an row-vector x(1,1)=1, x(1,2)=2, ... x(1,5)=5
x = [x; 2, 3, 4, 6, 7]; // add to 'x' a row.
// Accessing an element of arrays:
// to retrieve/print element of matrix 'x' just put this in a single line in the script
i=1;
j=2;
x[i;j]
## RPG
Works with: ILE RPG
//-Static array
//--def of 10 el array of integers, initialised to zeros
D array...
D s 10i 0 dim(10)
D inz
//--def an el
D el_1...
D s 10i 0 inz
/free
//-assign first el
//--first element of RPG array is indexed with 1
array(1) = 111;
//-get first el of array
el_1 = array(1);
//--display it
dsply ('First el of array='+%char(el_1));
//--displays: First el of array=111
//---or shorter, without "el_1"
dsply ('First el of array='+%char(array(1)));
//--displays: First el of array=111
/end-free
## Ring
Dynamic
# create an array with one string in it
a = ['foo']
a + 1 # ["foo", 1]
# set the value at a specific index in the array
a[1] = 2 # [2, 1]
# retrieve an element
see a[1]
## Ruby
Dynamic
# create an array with one object in it
a = ['foo']
# the Array#new method allows several additional ways to create arrays
# push objects into the array
a << 1 # ["foo", 1]
a.push(3,4,5) # ["foo", 1, 3, 4, 5]
# set the value at a specific index in the array
a[0] = 2 # [2, 1, 3, 4, 5]
# a couple of ways to set a slice of the array
a[0,3] = 'bar' # ["bar", 4, 5]
a[1..-1] = 'baz' # ["bar", "baz"]
a[0] = nil # [nil, "baz"]
a[0,1] = nil # ["baz"]
# retrieve an element
puts a[0]
## Run BASIC
print "Enter array 1 greater than 0"; : input a1
print "Enter array 2 greater than 0"; : input a2
dim chrArray\$(max(a1,1),max(a2,1))
dim numArray(max(a1,1),max(a2,1))
chrArray\$(1,1) = "Hello"
numArray(1,1) = 987.2
print chrArray\$(1,1);" ";numArray(1,1)
## Rust
The Rust book has a tutorial on arrays.
By default, arrays are immutable unless defined otherwise.
let a = [1, 2, 3]; // immutable array
let mut m = [1, 2, 3]; // mutable array
let zeroes = [0; 200]; // creates an array of 200 zeroes
To get the length and iterate,
let a = [1, 2, 3];
a.len();
for e in a.iter() {
e;
}
Accessing a particular element uses subscript notation, starting from 0.
let names = ["Graydon", "Brian", "Niko"];
names[1]; // second element
Dynamic arrays in Rust are called vectors.
let v = vec![1, 2, 3];
However, this defines an immutable vector. To add elements to a vector, we need to define v to be mutable.
let mut v = vec![1, 2, 3];
v.push(4);
v.len(); // 4
## Sather
-- a is an array of INTs
a :ARRAY{INT};
-- create an array of five "void" elements
a := #ARRAY{INT}(5);
-- static creation of an array with three elements
b :ARRAY{FLT} := |1.2, 1.3, 1.4|;
-- accessing an array element
c ::= b[0]; -- syntactic sugar for b.aget(0)
-- set an array element
b[1] := c; -- syntactic sugar for b.aset(1, c)
-- append another array
b := b.append(|5.5|);
## Scala
Arrays are not used often in Scala, since they are mutable and act differently to other collections with respect to type erasure, but are necessary for interoperability with Java. Alternatives such as List, Seq, and Vector are more commonly used.
// Create a new integer array with capacity 10
val a = new Array[Int](10)
// Create a new array containing specified items
val b = Array("foo", "bar", "baz")
// Assign a value to element zero
a(0) = 42
// Retrieve item at element 2
val c = b(2)
Dynamic arrays can be made using ArrayBuffers:
val a = new collection.mutable.ArrayBuffer[Int]
a += 5 // Append value 5 to the end of the list
a(0) = 6 // Assign value 6 to element 0
## Scheme
Lists are more often used in Scheme than vectors.
(let ((array #(1 2 3 4 5)) ; vector literal
(array2 (make-vector 5)) ; default is unspecified
(array3 (make-vector 5 0))) ; default 0
(vector-set! array 0 3)
(vector-ref array 0)) ; 3
## Seed7
By default array indices have the type integer and start from 1. Other index types and start values are also possible. E.g.: The famous arrays with indices starting from 0 are possible. Every type, which can be mapped to integer, can be used as index type.
\$ include "seed7_05.s7i";
const type: charArray is array [char] string; # Define an array type for arrays with char index.
const type: twoDim is array array char; # Define an array type for a two dimensional array.
const proc: main is func
local
var array integer: array1 is 10 times 0; # Array with 10 elements of 0.
var array boolean: array2 is [0 .. 4] times TRUE; # Array with 5 elements of TRUE.
var array integer: array3 is [] (1, 2, 3, 4); # Array with the elements 1, 2, 3, 4.
var array string: array4 is [] ("foo", "bar"); # Array with string elements.
var array char: array5 is [0] ('a', 'b', 'c'); # Array with indices starting from 0.
const array integer: array6 is [] (2, 3, 5, 7, 11); # Array constant.
var charArray: array7 is ['1'] ("one", "two"); # Array with char index starting from '1'.
var twoDim: array8 is [] ([] ('a', 'b'), # Define two dimensional array.
[] ('A', 'B'));
begin
writeln(length(array1)); # Get array length (= number of array elements).
writeln(length(array2)); # Writes 5, because array2 has 5 array elements.
writeln(array4[2]); # Get array element ("bar"). By default array indices start from 1.
writeln(array5[1]); # Writes b, because the indices of array5 start from 0.
writeln(array7['2']); # Writes two, because the indices of array7 start from '1'.
writeln(array8[2][2]); # Writes B, because both indices start from 1.
writeln(minIdx(array7)); # Get minumum index of array ('1').
array3[1] := 5; # Replace element. Now array3 has the elements 5, 2, 3, 4.
writeln(remove(array3, 3)); # Remove 3rd element. Now array3 has the elements 5, 2, 4.
array1 := array6; # Assign a whole array.
array1 &:= [] (13, 17); # Append an array.
array1 &:= 19; # Append an element.
array1 := array3[2 ..]; # Assign a slice beginning with the second element.
array1 := array3[.. 5]; # Assign a slice up to the fifth element.
array1 := array3[3 .. 4]; # Assign a slice from the third to the fourth element.
array1 := array3[2 len 4]; # Assign a slice of four elements beginning with the second element.
array1 := array3 & array6; # Concatenate two arrays and assign the result to array1.
end func;
## Self
The vector protorype represents a fixed size array with polymorphic contents. Vector indexing is zero based. Fixed size means that once created it is expensive (although not strictly impossible) to resize it. If resizable sequenced collections are wanted, the 'sequence' prototype can be used.
Creating simple vectors:
vector copySize: 100
vector copySize: 100 FillingWith: anObject
A polymorphic vector:
(1 & 'Hello' & 2.0 & someObject) asVector
Using a vector:
|v|
"creates an vector that holds up to 20 elements"
v: vector copySize: 20.
"access the first element"
v first printLine.
"access the 10th element"
(v at: 9) printLine.
"put 100 as second value"
vat: 1 Put: 100.
Enumeration:
v do: [:each | each printLine].
v copy mapBy: [:each | each squared].
v copy filterBy: [:each | each > 10].
Using a squence:
|s|
"creates a new sequence"
s: sequence copyRemoveAll.
"access the first element"
s first printLine.
"remove the first element"
s removeFirst.
"Check size"
s size printLine.
## Sidef
# create an empty array
var arr = [];
# push objects into the array
arr << "a"; #: ['a']
arr.append(1,2,3); #: ['a', 1, 2, 3]
# change an element inside the array
arr[2] = "b"; #: ['a', 1, 'b', 3]
# set the value at a specific index in the array (with autovivification)
arr[5] = "end"; #: ['a', 1, 'b', 3, nil, 'end']
# resize the array
arr.resize_to(-1); #: []
# slice assignment
arr[0..2] = @|('a'..'c'); #: ['a', 'b', 'c']
# indices as arrays
var indices = [0, -1];
arr[indices] = ("foo", "baz"); #: ['foo', 'b', 'baz']
# retrieve multiple elements
var *elems = arr[0, -1]
say elems #=> ['foo', 'baz']
# retrieve an element
say arr[-1]; #=> 'baz'
## Slate
slate[1]> #x := ##(1 2 3).
{1. 2. 3}
slate[2]> x
{1. 2. 3}
slate[3]> #y := {1 + 2. 3 + 4. 5}.
{3. 7. 5}
slate[4]> y at: 2 put: 99.
99
slate[5]> y
{3. 7. 99}
slate[6]> x first
1
slate[7]> x at: 0.
1
## Smalltalk
The Array class represents fixed size vectors with polymorphic contents. Array indexing is ONE-based. Fixed size means, that once created it is expensive (although not strictly impossible), to resize it (not strictly impossible because we could allocate a new array and #become that the old one). Most Smalltalks also provide element type restricted arrays, which are tuned (usually space-wise) for particular elements. For example: ByteArray, IntegerArray, LongIntegerArray, FloatArray or DoubleArray. Instances of them are also used to pass bulk data in and out of FFI calls (for example, for OpenGL). Also Strings can be seen as arrays of characters. All collection classes share a rich common protocol, which includes enumeration, stream converting, concatenation, copying, replacing, searching etc.
Finally, there is OrderedCollection, which behaves similar to Array, but allows for the number of elements to be changed (i.e. elements can be added and removed later). Usually, adding/removing at either end is cheap, so they can be used to implement stacks and queues.
Literal Arrays (Array constants):
#(1 2 3 'four' 5.0 true false nil (10 20) \$a)
a polymorphic array containing integers, a string, a float, booleans, a nil, another array with integers and a character constant.
Programatic use:
|array|
"creates an array that holds up to 20 elements"
array := Array new: 20 .
"access the first element: array base is 1"
(array at: 1) displayNl.
"put 100 as second value; you can put any object,
in particular SmallInteger"
array at: 2 put: 100.
"initialize an array from a 'constant' given array"
array := Array withAll: #('an' 'apple' 'a' 'day' 'keeps' 'the' 'doctor' 'away').
"Replacing apple with orange"
array at: 2 put: 'orange'.
"assigning values to an array"
"suppose array is bound to an array of 20 values"
array at: 5 put: 'substitute fifth element'.
[ array at: 21 put: 'error' ]
on: SystemExceptions.IndexOutOfRange
do: [ :sig | 'Out of range!' displayNl ].
"retrieving a value from an array"
#(\$a \$b \$c) at: 2
Enumeration:
array do:[:each | each printOn: aStream ]
array collect:[:each | each squared|
array select:[:each | each > 10]
Works with: Pharo
Works with: Smalltalk/X
Works with: Squeak
Constructing an Array from evaluated expressions:
{ Time now . 10 . Date today . 'foo' }
this construct evaluates each expression and creates a 4-element array containing a time, int, date and string object.
OrderedCollection:
oc := OrderedCollection withAll: #(4 5 6).
foo := oc removeFirst.
oc removeLast.
oc at:2 put: 'someString'.
oc asArray printCR.
oc2 := oc copyFrom:5 to:10
oc indexOf: 'someString'
oc findFirst:[:el | el isString]
"hundreds of other methods skipped here.."
## SNOBOL4
SNOBOL4 supports multi-dimensional arrays and array initialization.
ar = ARRAY("3,2") ;* 3 rows, 2 columns
fill i = LT(i, 3) i + 1 :F(display)
ar<i,1> = i
ar<i,2> = i "-count" :(fill)
display ;* fail on end of array
j = j + 1
OUTPUT = "Row " ar<j,1> ": " ar<j,2>
+ :S(display)
END
Output:
Row 1: 1-count
Row 2: 2-count
Row 3: 3-count
## SSEM
At the machine level, an array is a block of sequential storage addresses. Modern computer architectures support arrays through indexed addressing, where the contents of a particular register can be used to provide an offset from some specified address. A program to find the sum of a four-element array beginning at address array might look, in pseudocode, like this:
load register 0, #0 ; running total
load register 1, #0 ; index
loop: add register 0, array+register 1
add register 1, #1
compare register 1, #4
branchIfLess loop
If we do not know in advance how many elements the array will have, we can mark the end with a special value (say, zero) and test for that. Again in pseudocode:
load register 0, #0 ; running total
load register 1, #0 ; index
loop: load register 2, array+register 1
compare register 2, #0
branchIfEqual done
add register 0, register 2
add register 1, #1
goTo loop
done: ; program continues with sum in register 0
On a machine like the SSEM, which has only one addressing mode and only one general-purpose register (the accumulator or c), we can achieve the same things using instruction arithmetic—also known as self-modifying code. Since an instruction that refers to address ${\displaystyle n+1}$ can be obtained by adding one to an instruction that refers to address ${\displaystyle n}$, the pseudocode to find the sum of a four-element array (and store it at address sum, which we assume initially holds zero) becomes:
loop: load accumulator, sum
instr: add accumulator, array
store accumulator, sum
compare accumulator, #(add accumulator, array+4)
branchIfEqual done
store accumulator, instr
goTo loop
done: ; program continues
We are now in a position to translate this algorithm into SSEM instructions and run it. As always, the SSEM version is a bit fiddlier than the pseudocode because the SSEM has no load or add instructions; but it follows the pseudocode as closely as the instruction set allows, so it should be comparatively readable. As a test, we shall sum an array of the first four positive integers—a very significant operation for the Pythagoreans of old—and halt with the accumulator holding the result.
10101000000000100000000000000000 0. -21 to c
11101000000000010000000000000000 1. Sub. 23
00101000000001100000000000000000 2. c to 20
00101000000000100000000000000000 3. -20 to c
10101000000001100000000000000000 4. c to 21
10000000000000100000000000000000 5. -1 to c
01001000000000010000000000000000 6. Sub. 18
00101000000001100000000000000000 7. c to 20
00101000000000100000000000000000 8. -20 to c
10000000000001100000000000000000 9. c to 1
01101000000000010000000000000000 10. Sub. 22
00000000000000110000000000000000 11. Test
01001000000001000000000000000000 12. Add 18 to CI
11001000000000000000000000000000 13. 19 to CI
10101000000000100000000000000000 14. -21 to c
00101000000001100000000000000000 15. c to 20
00101000000000100000000000000000 16. -20 to c
00000000000001110000000000000000 17. Stop
10000000000000000000000000000000 18. 1
11111111111111111111111111111111 19. -1
00000000000000000000000000000000 20. 0
00000000000000000000000000000000 21. 0
11011000000000010000000000000000 22. Sub. 27
10000000000000000000000000000000 23. 1
01000000000000000000000000000000 24. 2
11000000000000000000000000000000 25. 3
00100000000000000000000000000000 26. 4
The program could easily be modified to work with arrays of unknown length, if required, along the lines of the second pseudocode example above.
## Suneido
array = Object('zero', 'one', 'two')
array[4] = 'four'
Print(array[3]) --> 'three'
## Swift
// Arrays are typed in Swift, however, using the Any object we can add any type. Swift does not support fixed length arrays
var anyArray = [Any]()
anyArray.append("foo") // Adding to an Array
anyArray.append(1) // ["foo", 1]
anyArray.removeAtIndex(1) // Remove object
anyArray[0] = "bar" // ["bar"]]
## Tcl
Tcl's lists are really dynamic array values behind the scenes. (Note that Tcl uses the term “array” to refer to an associative collection of variables.)
set ary {}
lappend ary 1
lappend ary 3
lset ary 0 2
puts [lindex \$ary 0]
Note also that serialization is automatic on treating as a string:
puts \$ary; # Print the whole array
## TI-83 BASIC
In TI-83 BASIC there are two sequenced data types: Lists and Matrices.
List
One dimensional arrays are lists, they can be set as a whole with the syntax:
{1,2,3,4,5}→L1
using only numerical values separated by commas and enclosed by curly braces.
Lists can be accessed as a whole using L1-L6 or a custom list name using the L command in the "OPS" section of the "LIST" menu (2nd STAT (Right Arrow) B). You can also retrieve a single value from a list using the name of the list and the position of the value, which starts at 1 on the left.
{1,2,3,4,5}→L1
Disp L1(3)
0→L1(4)
This would return 3 and set the fourth list element to 0.
You can dynamically define or delete lists by:
20→dim(L1)
DelVar L1
5→dim(∟MYLIST)
DelVar ∟MYLIST
Matrix
Two dimensional arrays are matrices. Similar, set them and retrieve numbers using the syntax:
[[11,21,31,41][12,22,32,42][13,23,33,43]]→[A]
Disp [A](1,3)
0→[A](4,2)
This would return 13 and set the element (4,2) to 0.
You can dynamically define or delete matrices by:
{5,5}→dim([A])
DelVar [A]
## TorqueScript
Arrays in TorqueScript:
\$array[0] = "hi";
\$array[1] = "hello";
for(%i=0;%i<2;%i++)
echo(\$array[%i]);
=> hi
=> hello
\$array["Greet",0] = "hi";
\$array["Greet",1] = "hello";
for(%i=0;%i<2;%i++)
echo(\$array["Greet",%i]);
=> hi
=> hello
## TXR
TXR has two kinds of aggregate objects for sequences: lists and arrays. There is some syntactic sugar to manipulate them in the same way.
#### Literals
In the pattern matching language, there are no list literals. A list like ("a" "b" "c") is actually being evaluated, as can be seen in a directive such as @(bind (a b) (c "d")) where (c "d") is a list consisting of the value of variable c and the string "d". This is subject to destructuring and the two values are assigned to the variables a and b
In TXR Lisp, there are literal lists introduced by a quote '(1 2 3 4). Vectors look like this: #(1 2 3 4).
#### Construction
Lists can be implicitly produced using pattern matching. Lists and vectors can be constructed using the functions of TXR Lisp. (vector 3) creates a vector of length three, whose elements are initialized to nil. (list 1 2 3) constructs the list (1 2 3).
#### Array Indexing Notation
The [] notation performs positional indexing on lists and arrays, which are both zero-based (element zero is the first element). Negative indices work from the tail of the list, whereby -1 denotes the last element of a sequence which has at least one element. Out of bounds access to arrays throws exceptions, but out of bounds access to lists produces nil. Out-of-bounds assignments are not permitted for either data type.
(defvar li (list 1 2 3)) ;; (1 2 3)
(defvar ve (vec 1 2 3)) ;; make vector #(1 2 3)
;; (defvar ve (vector 3)) ;; make #(nil nil nil)
[ve 0] ;; yields 1
[li 0] ;; yields 1
[ve -1] ;; yields 3
[li 5] ;; yields nil
[li -50] ;; yields nil
[ve 50] ;; error
(set [ve 2] 4) ;; changes vector to #(1 2 4).
(set [ve 3] 0) ;; error
(set [ve 3] 0) ;; error
#### Array Range Notation
Array range notation (slices) are supported, for both arrays and lists. An array range is a pair object denoted a .. b, which is a syntactic sugar for (cons a b). Therefore, a range constitutes a single argument in the bracket notation (allowing for straightforward future extension to multi-dimensional arrays indexing and slicing).
[ve 0..t] ;; yield all of vector: t means "one position past last element"
[ve nil..nil] ;; another way
[ve 1 3] ;; yields #(2 3)
(set [ve 0 2] '(a b)) ;; changes vector to #(a b 3)
(set [ve 0 2] #(1 2)) ;; changes vector to #(1 2 3)
(set [li 0 1] nil) ;; changes list to #(2 3), deleting 1.
(set [li t t] '(4 5)) ;; changes list to #(2 3 4 5), appending (4 5)
(set [ve 1 2] '(0 0)) ;; changes vector to #(1 0 0 3), replacing 2 with 0 0
#### In The Pattern Language
In the TXR pattern language, there is an array indexing and slicing notation supported in output variables. The following assumes that variable a holds a list.
@(output)
here is a[0] left-adjusted in a 10 character field:
@{a[0] 10}.
here are a[1] through a[3] joined with a colon,
right-adjusted in a 20 character field:
@{a[1..4] ":" -20}
@(end)
A complete program which turns comma-separated into tab-separated, where the first and last field from each line are exchanged:
@(collect)
@line
@(bind f @(split-str line ","))
@(output)
@{f[-1]}@\t@{f[1..-1] "\t"}@\t@{f[0]}
@(end)
@(end)
#### Other Kinds of Objects
The [] notation also works with strings, including ranges and assignment to ranges.
Hash tables can be indexed also, and the notation is meaningful for functions: [fun args ...] means the same thing as (call fun args ...), providing a Lisp-1 flavor within a Lisp-2 dialect.
## uBasic/4tH
uBasic/4tH has only one single, global array of 256 integers. Since it's fixed, it can't be declared.
Let @(0) = 5 : Print @(0)
## UNIX Shell
Bash supports one-dimensional arrays, which are zero-indexed. Zero-indexing means that if the array has five items in it, the first item is at index 0, and the last item is at index 4.
Two-dimensional arrays can be accomplished using shell functions applied to arrays of array names. Basically, hiding the indirection within the shell function invocation.
To create an array:
alist=( item1 item2 item3 ) # creates a 3 item array called "alist"
declare -a list2 # declare an empty list called "list2"
declare -a list3[0] # empty list called "list3"; the subscript is ignored
# create a 4 item list, with a specific order
list5=([3]=apple [2]=cherry [1]=banana [0]=strawberry)
To obtain the number of items in an array:
count=\${#alist[*]}
echo "The number of items in alist is \${#alist[*]}"
To iterate up over the items in the array:
x=0
while [[ \$x < \${#alist[*]} ]]; do
echo "Item \$x = \${alist[\$x]}"
: \$((x++))
done
To iterate down over theitems in an array:
x=\${#alist[*]} # start with the number of items in the array
while [[ \$x > 0 ]]; do # while there are items left
: \$((x--)) # decrement first, because indexing is zero-based
echo "Item \$x = \${alist[\$x]}" # show the current item
done
To append to an array, use the current number of items in the array as the next index:
alist[\${#alist[*]}]=new_item
To make appending easier, use a little shell function, let's call it "push", and design it to allow appending multiple values, while also preserving quoted values:
# shell function to append values to an array
# push LIST VALUES ...
push() {
local var=\${1:?'Missing variable name!'}
shift
eval "\\$\$var=( \"\\${\$var[@]}\" \"\$@\" )"
}
push alist "one thing to add"
push alist many words to add
To delete a single array item, the first item:
unset alist[0]
To delete and return the last item in an array (e.g., "pop" function):
# pop ARRAY -- pop the last item on ARRAY and output it
pop() {
local var=\${1:?'Missing array name'}
local x ; eval "x=\\${#\$var[*]}"
if [[ \$x > 0 ]]; then
local val ; eval "val=\"\\${\$var[\$((--x))]}\""
unset \$var[\$x]
else
echo 1>&2 "No items in \$var" ; exit 1
fi
echo "\$val"
}
alist=(a b c)
pop alist
a
pop alist
b
pop alist
c
pop alist
No items in alist
To delete all the items in an array:
unset alist[*]
To delete the array itself (and all items in it, of course):
unset alist
## உயிர்/Uyir
இருபரிமாணணி வகை எண் அணி {3, 3};
இருபரிமாணணி2 வகை எண் அணி {3} அணி {3};
என்_எண்கள் வகை எண் {#5.2} அணி {5} = {3.14, 2.83, 5.32, 10.66, 14};
சொற்கள் வகை சரம் {25} அணி {100};
உயரங்கள் = அணி {10, 45, 87, 29, 53};
பெயர்கள் = அணி {"இராஜன்", "சுதன்", "தானி"};
தேதிகள் = அணி {{5, "மாசி", 2010}, {16, "புரட்டாசி", 1982}, {22, "ஆவணி", 1470}};
செவ்வகணி = அணி { அணி {10, 22, 43}, அணி {31, 58, 192}, அணி {46, 73, 65} };
முக்கோண்ணி = அணி { அணி {1}, அணி {2, 3}, அணி {4, 5, 6}, அணி {7, 8, 9, 1, 2} };
## Vala
Non-dynamic arrays:
int[] array = new int[10];
array[0] = 1;
array[1] = 3;
stdout.printf("%d\n", array[0]);
Library: Gee
Dynamic Arrays with Gee:
var array = new ArrayList<int> ();
array[0] = 2;
stdout.printf("%d\n", array[0]);
## Vim Script
Lists can be used for dynamic arrays. Indexing starts at 0.
" Creating a dynamic array with some initial values
let array = [3, 4]
" Retrieving an element
let four = array[1]
" Modifying an element
let array[0] = 2
" Appending a new element
" Prepending a new element
call insert(array, 1)
" Inserting a new element before another element
call insert(array, 3, 2)
echo array
Output:
[1, 2, 3, 4, 5]
## Visual Basic .NET
'Example of array of 10 int types:
Dim numbers As Integer() = New Integer(0) {}
'Example of array of 4 string types:
Dim words As String() = {"hello", "world", "from", "mars"}
'You can also declare the size of the array and initialize the values at the same time:
Dim more_numbers As Integer() = New Integer(2) {21, 14, 63}
'For Multi-Dimensional arrays you declare them the same except for a comma in the type declaration.
'The following creates a 3x2 int matrix
Dim number_matrix As Integer(,) = New Integer(2, 1) {}
'As with the previous examples you can also initialize the values of the array, the only difference being each row in the matrix must be enclosed in its own braces.
Dim string_matrix As String(,) = {{"I", "swam"}, {"in", "the"}, {"freezing", "water"}}
'or
Dim funny_matrix As String(,) = New String(1, 1) {{"clowns", "are"}, {"not", "funny"}}
Dim array As Integer() = New Integer(9) {}
array(0) = 1
array(1) = 3
Console.WriteLine(array(0))
'Dynamic
Imports System
Imports System.Collections.Generic
Dim list As New List(Of Integer)()
list(0) = 2
Console.WriteLine(list(0))
## Wren
var arr = []
arr.count // 2
arr.clear()
arr.add(arr[-1]) // [0, 0, 1, 1]
arr[-1] = 0
arr.insert(-1, 0) // [0, 0, 1, 0, 0]
arr.removeAt(2) // [0, 0, 0, 0]
## X86 Assembly
section .text
global _start
_print:
mov ebx, 1
mov eax, 4
int 0x80
ret
_start:
;print out our byte array. ergo, String.
mov edx, sLen
mov ecx, sArray
call _print
mov edx, f_len
mov ecx, f_msg
call _print
mov edx, 6 ;our array members length.
xor ecx, ecx
mov ecx, 4
;turnicate through the array and print all it's members.
;At an offset of *4, each array member is referenced
;at 1,2,3 and so on.
_out_loops:
push ecx
mov ecx, [fArray+esi*4]
call _print
inc esi
pop ecx
loop _out_loops
mov edx, u_len
mov ecx, u_msg
call _print
;Let's populate 'uArray' with something from sArray.
;mov edi, uArray
mov ecx, 4
xor esi, esi
push dword [fArray+esi*4]
pop dword [uArray+esi*4]
inc esi
mov ecx, 4
xor esi, esi
_out_loops2:
push ecx
mov ecx, [uArray+esi*4]
call _print
inc esi
pop ecx
loop _out_loops2
push 0x1
mov eax, 1
push eax
int 0x80
section .data
sArray db 'a','r','r','a','y','s',' ','a','r','e',' ','f','u','n',0xa
sLen equ \$-sArray
crap1 db "crap1",0xa
crap2 db "crap2",0xa
crap3 db "crap3",0xa
crap4 db "crap4",0xa
fArray dd crap1,crap2
dd crap3,crap4
f_msg db "fArray contents",0xa,"----------------------",0xa
f_len equ \$-f_msg
u_msg db "uArray now holds fArray contents.. dumping..",0xa,"----------------------",0xa
u_len equ \$-u_msg
section .bss
uArray resd 1
resd 1
resd 1
resd 1
Arrays in assembly are a reference to anything, from groups of data such as f/uArray to strings like _msg's or sArray. Mutlidimentional arrays don't exist in assembly. To make a reference to one from assembly, we use a format as such. "row * r_len + column * member_size".
## XLISP
Like some other languages, XLISP refers to one-dimensional arrays as vectors. Examples of vector and array syntax, from a REPL (interactive session):
[1] (define a (make-vector 10)) ; vector of 10 elements initialized to the empty list
A
[2] (define b (make-vector 10 5)) ; vector of 10 elements initialized to 5
B
[3] (define c #(1 2 3 4 5 6 7 8 9 10)) ; vector literal
C
[4] (vector-ref c 3) ; retrieve a value -- NB. indexed from 0
4
[5] (vector-set! a 5 1) ; set a_5 to 1
1
[6] (define d (make-array 5 6 7)) ; 3-dimensional array of size 5 by 6 by 7
D
[7] (array-set! d 1 2 3 10) ; set d_1,2,3 to 10 -- NB. still indexed from 0
10
[8] (array-ref d 1 2 3) ; and get the value of d_1,2,3
10
## XPL0
include c:\cxpl\codes;
char A(10); \creates a static array of 10 bytes, pointed to by "A"
char B; \declares a variable for a pointer to a dynamic array
[A(3):= 14;
B:= Reserve(10); \reserve 10 bytes and point to their starting address
B(7):= 28;
IntOut(0, A(3)+B(7)); \displays 42
]
## zkl
Core zkl does not support arrays or vectors of one type. It does support heterogeneous lists, which are usually a super set at the cost of space.
var array=List(); // array of size 0
array=(0).pump(10,List().write,5).copy(); // [writable] array of size 10 filled with 5
array[3]=4;
array[3] //-->4
array+9; //append a 9 to the end, same as array.append(9)
10 DIM a(5)
20 LET a(2)=128
30 PRINT a(2)
|
{}
|
## Refining Structured Type System
This is my first more serious paper on Structured Type System.
[Abstract]
...
As every theory needs some syntax form to express its elements, a road to a theory about theories leads through a syntax defining land, so structured type system, in the first place, provides a flexible generalized text parser that builds up internal abstract syntax trees (AST) from input data. The other aspect of theory about theories inevitably covers the meaning of input data. This is called semantics, and this is the point where structured type system provides a possibility to define deeper connections between syntactic elements of AST-s. For this purpose, structured type system uses a kind of functions known from functional programming paradigm. These functions are able to process any data corpus, being natural or artificial language translation, which in turn happens to be just enough for running any complexity task used to analyze existing and calculate new data from an input.
...
In short, we use BNF-ish grammars as types for function parameters and function results. Some nice constructions can be made by combining grammars and functions. One of the most important properties of structured type system is its ability to additionally extend grammars outside the grammars definitions, all based on function result types. It is fairly simple: where a certain type of expression is expected, there a grammar that results with the same type can be used, and there goes syntax extensibility. Conveniently, we can combine grammar definitions and their inputs in the same source code file.
I was hoping to get some feedback and critics from this community before attempting to get more publicity to the paper. This is an important milestone to me and I want to thank You all for being so inspirational community during my research.
## Comment viewing options
### Nice
It's very interesting and I want to mine it for ideas on extensible syntax. One thing I wonder about is the interoperability between different syntaxes and the introduction of "higher order" notations. For example, imagine I would like to share the notion of BinaryOp between boolean algebra and arithmetic expressions, and I want to introduce shorthand that applies to all binary expressions, like slice notation, e.g. (< 2). Can that be encoded in a natural way? Or even more challenging, could you introduce a shorthand for introducing new binary operators that allows you to name their precedence relative to other operators?
### Higher order notations
could be managed either by (1) dependent terms (aka dependent types), either by (2) metaprogramming that is handled in a natural way of thinking. In the case of metaprogramming, after applying parameters to a function, the function could return a case-expression controlled parts or wholes of sequences, alternations, implications, or even another functions. It seems that metaprogramming takes a full swing with structured type system.
### Precedence of operators
Precedence of operators is somewhat complex matter. It is meant to be handled from the starting first syntax definition and taking care on further syntax extensions. Let's see an example of simple math calculator:
@Parsed ( Sum <- ( ( Add <- ( Left <- @Sum, "+", Right <- @Fact ) ) => @DefaultMath (@Add.Left + @Add.Right) | Fact <- ( ( Mul <- ( Left <- @Fact, "*", Right <- @Primary ) ) => @DefaultMath (@Mul.Left * Mul.Right) | Primary <- ( Integer <- @Int ) ) ) )
Now we want to extend this syntax by exponential operator. To control its precedence, we have to pick symbols of the depth of our interest. If we want it to have the highest precedence, we have to put it between symbols "@Sum.Fact.Primary" and "@Sum.Fact.Primary.Integer":
@Parsed ( ( Pow <- ( Left <- @Sum.Fact.Primary, "^", Right <- @Sum.Fact.Primary.Integer ) ) => @DefaultMath (@Pow.Left ^ @Pow.Right) )
If we want the same precedence as multiplication, we put it between symbols "@Sum.Fact" and "@Sum.Fact.Primary":
@Parsed ( ( Pow <- ( Left <- @Sum.Fact, "^", Right <- @Sum.Fact.Primary ) ) => @DefaultMath (@Pow.Left ^ @Pow.Right) )
If we want the same operator precedence as addition, we put it between symbols "@Sum" and "@Sum.Fact":
@Parsed ( ( Pow <- ( Left <- @Sum, "^", Right <- @Sum.Fact ) ) => @DefaultMath (@Pow.Left ^ @Pow.Right) )
But, if we want the least precedence, have to write a wrapper above "@Sum":
@Parsed ( Exp <- ( ( Pow <- ( Left <- @Exp, "^", Right <- @Sum ) ) => @DefaultMath (@Pow.Left ^ @Pow.Right) | Sum <- @Sum ) )
In all cases, we can call "@Sum (1+2*3^4)".
### Numeric Precedence
Personally I prefer to define the precedence of an operator as a number, which allows the precedence of any operator to be changed independently of other operators. This can be achieved with something like a Pratt parser.
### Metaprogramming
I'd have to check it with metaprogramming. Theoretically, it should be possible to generically construct a compound term with this or that precedence of its subterms, as a result of a function which would take the subterms and their precedence numbers as parameters.
### A shortcut to switching precedence order of binary operations
Here it is:
(
List <- ( // a typed list
(Type <- @Any) => (
Item <- @Type,
Next <- (@List (@Type) | @Unit) // @Unit is used to denote the end of a list
)
) |
BinOp <- ( // afterwards we will pass these in a list
Op <- @String,
Calc <- (
(Left <- @Int, Right <- @Int) => @Int
) // and we will pass functions needed for calculations here
) |
Main <- (
BinOpCalc <- (
(
Operators <- @List (@BinOp) // here we take a list of operators
) => @Parsed (
(
Iterator <- (
(I <- @List) => (
@Iff (@I == @Unit, // if we reached the last item
@Int, // this is recursion terminator
Parent <- ( // otherwise, this is basic parser parent-child pattern
(
(
// here we parse specific operator
(Left <- @Parent, @I.Item.Op, Right <- @Child)
) => (
// and here we calculate it
@I.Item.Calc (@Left, @Right)
)
) |
Child <- @Iterator (@I.Next) // recursing the iterator
)
)
)
)
) (@Operators) // we apply the list to iterator
)
)
)
).Main // exposing BinOpCalc to outer space
...
// default math precedence order. Precedence is determined by a position in list
x <- @BinOpCalc (
("+", (Left <- @Int, Right <- @Int) => @DefaultMath (@Left + @Right)),
("*", (Left <- @Int, Right <- @Int) => @DefaultMath (@Left * @Right)),
("^", (Left <- @Int, Right <- @Int) => @DefaultMath (@Left ^ @Right))
)
...
x1 <- @x (1+2*3^4) // x1 now holds the result of 1+(2*(3^4)), that is 163
...
// reversed precedence order
y <- @BinOpCalc (
("^", (Left <- @Int, Right <- @Int) => @DefaultMath (@Left ^ @Right)),
("*", (Left <- @Int, Right <- @Int) => @DefaultMath (@Left * @Right)),
("+", (Left <- @Int, Right <- @Int) => @DefaultMath (@Left + @Right))
)
...
y1 <- @y (1+2*3^4) // y1 now holds the result of ((1+2)*3)^4, that is 6561
...
// mixed precedence order
z <- @BinOpCalc (
("^", (Left <- @Int, Right <- @Int) => @DefaultMath (@Left ^ @Right)),
("+", (Left <- @Int, Right <- @Int) => @DefaultMath (@Left + @Right)),
("*", (Left <- @Int, Right <- @Int) => @DefaultMath (@Left * @Right))
)
...
z1 <- @z (1+2*3^4) // z1 now holds the result of (1+(2*3))^4, that is 2401
### Same precedence
What about operator like "+" and "-" that normally have the same precedence as binary operators?
### It is fairly simple
It is fairly simple to do it. In the "basic parser parent-child pattern" part (see the commented code above), we have to generically unfold elements that have the same operator precedence to an alternation representing them, instead of a single element between Parent and Child. Of course, to express the same precedence, we have to change input parameters structure also.
For example, here is how to generically construct an alternation from a list:
( Iterator <- ( (I <- @List) => ( @Iff (@I == @Unit, // remember that @List is terminated by @Unit @None, // we terminate the recursion by the empty alternation ( @I | // this is an alternation member @Iterator (@I.Next) // this is the rest of alternations ) ) ) ) ) (@SomeList)
Certainly, of the great usability are terms @None (that stands for the empty alternation) and @Unit (that stands for the empty sequence).
@None has these properties:
(X | @None) === X (@None | X) === X (X | @None | Y) === (X | Y)
while @Unit has these properties:
(X, @Unit) === X (@Unit, X) === X (X, @Unit, Y) === (X, Y)
@None can be used to terminate generic alternations, while @Unit can be used to terminate generic sequences. The third term from a triad is @Any that stands for any concievable term in structured type system, and can be used to pass around unapplied or applied terms (so functions also, as a function is a term).
These are great questions. I think I'll include them in the final version of the paper if I have your permission.
### Associativity for Precedence
Personally I find numeric precedence hard work: is 1 most binding or least binding? (Different languages vary.)
Are 9 precedence levels enough? Consider (for example) all the operators introduced in the Lens libraries, or in a typical DSL.
Yes you need to be able to change the precedence for individual operators. Perhaps there are different ways to skin that cat.
Suppose you could declare precedences as Associativity rules, and let the compiler figure it out. Your rules look like:
-- ==> is the rewrite-as declaration x + y ^ z * w ==> x + ((y ^ z) * w) ; x > y && z + w == v -> NOT q ==> ((x > y) && ((z + w) == v)) -> (NOT q)
### So those are examples rather than rules?
In that case, you could adopt a convention that all parens in the example should be removable and just write:
precedence example ((x > x) && ((x + x) == x)) -> (NOT x)
### An operator precedence technique
In a paper Operator Precedence for Data-Dependent Grammars, found on Iguana parser site, I just saw a nice and clean method for managing operator precedence when dealing with data-dependent grammars (as they call it). Translated to structured type system, we get:
( Exp <- ( (p <- @Int) => @Case ( (@p >= 3) => (@Exp (3), ('+' | '-'), @Exp (2)) | (@p >= 2) => (@Exp (2), ('*' | '/'), @Exp (1)) | (@p >= 1) => (@Exp (1), ('^' | '√'), @Exp (0)) | (@p >= 0) => /[0-9]+/ ) ) ) (3)
I never doubted that human ingenuity has no limits, and this is no exception. Ali Afroozeh and Anastasia Izmaylova, thank You :)
### Shorthand
Shorthand that applies to all binary expressions? I'm not sure what you mean.
### Sections of operators
In Haskell, you can write (+ 1) for (\x -> x+1) or (< 1) for (\x -> x < 1). Essentially it partially applies the operator to a single operand, producing a unary function. This notation is preferably something you'd specify you'd specify once for all Binary Operators.
### Slice
Here it is:
( Op <- ( Plus <- "+" | Times <- "*" | Power <- "^" ) | OpImplementation <- ( (Left <- @Int, In <- @Op, Right <- @Int) => ( ( @Op.Plus => @DefaultMath (@Left + @Right) | @Op.Times => @DefaultMath (@Left * @Right) | @Op.Power => @DefaultMath (@Left ^ @Right) ) (@In) ) ) | Main <- ( Slice <- ( @Parsed ( Op <- @OpImplementation.In, Right <- @OpImplementation.Right, ) => ( (Apply <- @Int) => @OpImplementation (@Apply, @Op, @Right) ) ) ) ).Main ... x <- @Slice (+3) // x now holds (Apply <- @Int) => @OpImplementation (@Apply, "+", 3) ... y <- @x (10) // y now holds 13 ... z <- @Slice (*3) (4) // z now holds 12
I left out formalities about handling optional whitespace.
### type specific languages
From your description, I am reminded of Jonathon Aldrich's work on the Wyvern language regarding type specific languages.
I generally like the idea of using the type system to guide interpretation of a program, except for the part where it doesn't easily work with 'interpretation' insofar as we need a static type checker and to process a bunch of grammars. My own approach to language extension has taken a decidedly different direction - focusing on projectional editors and editable views. But I'll take a deeper gander at your work, and I should probably review Wyvern's again too.
### Graphical interfaces
Yes, I remember your idea of graphical interfaces to a source code, Dmbarbour, and I liked it very much. There is a big potential in that idea. What we have in the computer industry today are hard-coded solutions of wisiwig editors. Imagine if the users could be ones who define such interfaces that could extend to other areas than wisiwig editing.
Each function that could have its own customized graphical interface would be a lot easier learning material. It would be a huge step in programming science.
### Abstract Categorial Grammars
If you haven't done it yet, you might be interested in checking out, also:
Towards Abstract Categorial Grammars
### Reducing the number of primitive operators
I've managed to express syntax building operator "<-" by function operator "=>" on which is immediately applied its left side! The type system then constructs a sequence flattened to terminal leafs of the whole expression. It turns out that type checking system concludes left function sides from those leafs, playing a role of a BNF-ish parser.
This is the "<-" definition as non-primitive operator:
@Parsed ( (A => @Symbol) (@A), '<-', (B => @Any) (@B) ) => @Parsed ( (@A => @B) (@A) )
Conclusion: Immediately applying all left sides of any function system transforms the function system into a parser system.
### Subtyping
Thinking further, syntax building "<-" operator is nothing more than regular subtype operator ":>" known from type theory. That means that subtyping can be expressed in a terms of functions and their parameters application, which in turn can play a role of BNF-ish syntax definition language.
### Suggestions?
I'm extending the paper to include some serious examples. I'm thinking of implementing some axiomatic set theory, but I'm not sure which one is the most recent. Simplicity also matters, and I would like to take some optimal least amount of definition rules, achieving the most complete realization.
Is Zermelo–Fraenkel set theory enough to get mathematicians interested, or does anyone have other suggestions?
### Negating types
May I ask a simple question? I've been playing with "negation" (complement, or whatever analog) operator on types, and forming universe types. It is clear that we may define:
• empty sum that may stand for nothing value
• empty product that may stand for unit value
As sum may be seen as existentially quantified set, and product may be seen as universally quantified set, I understand that they are interchangeable by the following expressions:
• ¬(∃x.P(x)) -> ∀x.¬P(x)
• ¬(∀x.P(x)) -> ∃x.¬P(x)
The question is: what types are formed when we "negate" empty sum and empty product? By the intuition derived from classical logic, this is what may happen:
• "negating" empty sum would give universally quantified anti-nothing set (all of nothingcomplement)
• "negating" empty product would give existentially quantified anti-unit set (any of unitcomplement)
Am I doing a mistake with this assumption? Is it really necessary to introduce anti-values like classical set complement, or we may just use the set of all elements? If anyone has a link, or an opinion with details on this kind of operation, I would highly appreciate if you would share it here. Thank you all in advance.
### Re: negating types
I think your framework is a bit messed up here.
The "empty sum" nothing value is just a value in type (1+a). You can't negate the value and speak of it as equivalent to negating the type. (Or do you mean an empty Sigma type?)
Also, the "empty product" is just one example of type 1. In many languages, the unit value and unit type are primitive. But type 1 is really just any type with a single inhabitant, and hence carrying no runtime data. For example, forall a . a->a or forall a,b,c. (a,b,c) -> (c,a,b). Naturally, there is an infinite set of unit types. We could feasibly use unit types to encode static data.
For logical negation, I'd recommend looking at the question through the lens of Curry-Howard correspondence and simpler Church encodings of data types. A sum type (a+b) can be encoded as forall c. (a -> c) -> (b -> c) -> c. A product (a*b) as forall c. (a -> b -> c) -> c. How would you complement these propositions? (Note that a -> b can be encoded in propositional logic as b or not a.)
Seems like a bunch of arrows should get turned around. I don't have a good intuition in general, but there is likely a relationship to duality in category theory. Sums and products are known to dual each other, for example. Try negation on lots of Church-encoded types, including a few single inhabitant types, to get an intuition. (My cold doesn't leave me up to doing this, but getting an intuition isn't something I could do for you anyway.)
### is Unit equal to any consistent type?
For logical negation, I'd recommend looking at the question through the lens of Curry Howard correspondence. And simpler Church encodings of types. A sum type can be encoded as forall a,b,c. (a->c) -> (b -> c) -> c. A product as forall a,b,c. (a -> b -> c) -> c. How would you complement these propositions? (Note that a -> b can be encoded in propositional logic as b or not a.)
I'm afraid that labmda calculus doesn't perfectly maps to propositional logic. True, some analogies hold, but generally, I think the problem is in the rightmost sides of nested functions.
Try negation on lots of types to get an intuition, and let me know what you learn.
this is where I come from: in logic, true corresponds to Unit, while false corresponds to Zero.
• Existential quantifier can be seen as a disjunction of set elements (sum).
Empty disjunction gives us false, by the book. If we negate it, we get true. However, isn't negation of empty disjunction a "full conjunction", a product of all elements not contained in the starting disjunction, which is empty? If this is true, then full conjunction equals true (see up). Note that empty conjunction also equals true.
Hence, empty conjunction == full conjunction == true == Unit.
Thinking further, couldn't we put *any* true formula wherever says true? And that is the most intriguing thing I've ran into lately: instead of true, we can write Unit, like we can write any true formula. Thus, Unit could stand for any true formula in specific rule set, including tautologies in general case, not only a constant true.
Drawing a parallel with a type system, Unit should stand for *any* conceivable type that is consistent.
• And now the analogy: universal quantifier can be seen as a conjunction of set elements (product).
Empty conjunction gives us true by the book. If we negate it, we get false. However, isn't negation of empty conjunction a "full disjunction", a sum of all elements not contained in the starting conjunction, which is empty? If this is true, then full disjunction equals false (see up). Note that empty disjunction also equals false.
Hence, empty disjunction == full disjunction == false == Zero.
Thinking further, couldn't we put *any* false formula wherever says false? And that is the more obvious analogy: instead of false, we can write Zero, like we can write any false formula. Thus, Zero could stand for any false formula in specific rule set, including contradictions in general case, not only a constant false.
Drawing a parallel with a type system, Zero should stand for *any* conceivable type that is erroneous.
The big question is: is Unit equal to any consistent type? It seems reasonable to think that an unit is one piece of something, whatever it is.
1) is empty sum equal to full sum, equal to Zero? Look in math, what do we get when we sum all the positive and all the negative numbers?
2) is empty product equal to full product, equal to Unit? Again, what would math say about product of all the numbers greater than or less than one?
I have a feeling that I opened a space wormhole here :-)
### (ignore)
In retrospect, I think it's better you just focus on the root logic errors rather than that boldface question... see next reply.
Regarding your bullet points: Negation of an empty disjunction is the empty conjunction. By De Morgan's law.
Rather than true and false you would be wiser to think in terms of satisfiability. Unit types are satisfiable in exactly one way, but are not equivalent to true because there are observations we can make other than satisfiability. To negate a proposition, we must use De Morgan's law to preserve structure for these other observations.
Also, I did not suggest mapping lambda calculus terms to propositional logic. I suggested mapping types of Church encodings to propositional logic. There's a big difference. For example, there is a countably infinite set of natural number terms, but they can all be represented under the same Church-encoding type forall a. a -> (a -> a) -> a. If you want to "negate" the type of natural numbers, that's a good place to start.
### Ok
Negation of an empty disjunction is the empty conjunction
Ok, got it. So "complement" of empty sum should equal to empty product, if I may. But that's not the case in math. -0 still equals 0.
I'd still pronounce Unit type as a type of all consistent types. It should be one of anything except Zero, somehow. I'm hoping for some arguments if I'm about to implement it in the language.
### Unit
You'll just end up confusing your future readers if you insist on using "unit" to describe "one of anything". It's "one of one thing". And consequently requires zero variable bits at runtime.
Also, you should not be so quick to conflate the sum data type directly with a logical disjunction. In type (a+b), the choice is exclusive. In (a+a) we need to somehow preserve ordering information. In proposition (a \/ b), it is not exclusive, and order is irrelevant.
I still recommend my suggestion from my first reply, regarding use of Curry-Howard correspondence on basic Church encoded types. But I won't try to convince you further.
### Church encoding
Actually, I kind of hope for following analogies:
empty sum == empty set == accepting no type
empty product == universe set == accepting any type
I'm still finding reasons to do it this way, I wouldn't like to just do it, I have to know what are the consequences. A motive is having defined all the basic boolean and other operations, including math and logic, in a consistent way. However, I might consider finding my own name to a universe set that "could be" a result of empty product in proposed new construct. Maybe XUnit.
I still recommend my suggestion from my first reply, regarding use of Curry-Howard correspondence on basic Church encoded types.
I didn't forget to check it out, I just didn't find any inspiration there. I'm somewhat familiar with Church encoding of numbers and operations on them in lambda calculus. Viewing them from the recent aspect, I didn't get further than having a disjunction of numbers. When we apply De Morgan's law, we get a negated conjunction of negations of the numbers. But, what could a logical negation mean for a number when a number isn't a boolean? The closest thing to a train of thought considering a set of numbers are again predicates "is element of" and "is not element of" set, possibly empty, which again lifts me out of internal number encoding structure. Do you have any other idea?
In a meanwhile, I also checked dependent product type (for universal quantifier) versus dependent sum type (for existential quantifier). Didn't ring my bell either.
### Negation and Numbers
Regarding the negation of numbers, you can't really do it in first order logic, because it involves infinite elements. 'not(3 \/ 2) is the infinite set of all numbers that are (not 3) and (not 2). Fundamentally logic (which deals only in truth) cannot do this. You need to introduce constraints.
Logic has one constraint, equality, as we can only ask if something is equal to true. To handle negation you need disequality as well. Then:
forall x . not(x = 2 \/ x = 3)
forall x . not(x = 2) /\ not(x = 3)
forall x . x /= 2 /\ x /= 3
### If we write
If we write:
forall x . x = 2
does it mean that
1) we set the (= 2) predicate as true for all x, or
2) we pick all x that are equal to 2?
### #1
Although I wouldn't think of it as "setting" it as such, but rather just a proposition that all x (out of some set?) are equal to 2. This could be proven true with a term taking all x to a term of type x=2.
### assertions vs. boolean check
So, if we write
forall x . not (x = 2)
we are actually not picking a set of x-es that are not equal 2. We are saying that no x equals 2. But aren't we asserting here that x is an element of {2}complement?
But, if we put it on the left side of a consequence:
forall x . not (x = 2) -> Interesting(x)
we are actually saying that for each x that is not equal 2, we know that x is interesting. Here we boolean check the set {2}complement.
There is something odd going on with logic, dealing with assertions (in the first case) versus boolean check (in the second case).
### Consequences
I think the first case is simply false, as if x can be literally anything then one of those things is 2.
You are right the second is more what I was intending, but I was trying to keep it as simple as possible.
### Negating types, not terms
You're eager to discuss negation of specific numbers, like 2 or 3. But in type systems, 2 and 3 just refer to types with two or three values respectively. Perhaps ask instead, what is the negation of type (1+1).
I'm not a fan of set theory or set-based models of types. They are a bad fit for substructural types, for example. I'd prefer to start from a constructive or computational logic.
Aside: I feel that you're trying to fit your intuition into a theory where instead (as a scientist of computing) you should be using examples you know to be valid to grasp a valid intuition or hypothesis and test your assumptions. The whole "finding reasons to do it this way" line (and many similar comments you've made) makes me feel suspicious about confirmation bias.
### Set theory models.
In computer science we are using types to define the interpretation of a region of objects in memory, where objects are simply extents. So what is the data from byte 32 to byte 36? Is it 4 characters, or an integer or a floating point number. They clearly are concrete representations that we are dealing with. The problems of mathematical set theory like the Russel paradox simply cannot happen. This is because the question what is the type of type is clearly absurd, as it has no representation in memory. The only way to do it is to put an enum in memory and match each value to a type. As long as we remember what types represent, you cannot go wrong.
### representation
This is because the question what is the type of type is clearly absurd, as it has no representation in memory.
Is the problem that it has no representation or that determining its representation is undecidable (or unsound as a logical principle, ie: Girard's paradox)?
The unit type has no representation in memory, nor do any types that terminate staging (e.g. quoted expression types, type-level values, compile-time network connections, etc).
Put in the terms you described it, you might have 4 bytes in memory and describe them as a tuple of one int and a million units, or a hundred units followed by an int followed by a quoted expression and a compile-time network connection, etc.
### The type of type
Both:
It is unsound logically: Any concrete value in memory is a value, and not a type by definition. So they bit pattern at address 1234 is a value, and a type is not a value. If a type is a value, then you fall foul of Russel's paradox, because you no longer have stratification, and that permits the question "that is the type of all types that are not members of themselves". This can be explained by considering a value like "1.2", is it a member of type "Int"? If types are values then it must be possible to have a Type of a Type (as we need a type to interpret the encoding of an extent of bytes), so now we can ask is "type-a" a member of "type-b" in the same way we can ask if any value is a member of any type.
In terms of representations, we cannot independently compile two modules for runtime linking and have them determine the 'values' of types, as we cannot guarantee that the same representation wont be used for different types. The closest we could get is to hash the structure of the type, but then a hash-collision would result in big problems. Still this may be good enough in practice for many situations, we still have the fundamental problem of the paradox above.
We can avoid these problems if we simply consider things in memory to be values, and types are something else.
### staging
If types are values then it must be possible to have a Type of a Type (as we need a type to interpret the encoding of an extent of bytes), so now we can ask is "type-a" a member of "type-b" in the same way we can ask if any value is a member of any type.
[...]
We can avoid these problems if we simply consider things in memory to be values, and types are something else.
I take your point that you can't say that 'type' has type 'type'. But isn't this "typical ambiguity" just resolved with nested "universes" or perhaps viewed another way -- ordered stages? Like "stage-0 type is a stage-1 type" and it's always possible to shunt something off to "the next stage".
I mean, as a practical matter, you might want to use '42' at stage-0 (compile time?) as in the type description 'char[42]' or you might want to use '42' at stage-1 (run time?) as in 'printf("%d",42)'.
In a similar way, you can have a memory representation for type descriptions and have a way to read/write them, and stage later computations predicated on the "value" of those type descriptions -- so at stage-0 you run a "typical value-level function" to read a type description from a file, which then determines how you interpret subsequent data in stage-1. We do this a lot in this project I've been working on, there's a lot of practical value to this view.
I guess I'm not really disagreeing with you but just trying to find the best language for thinking about these issues of types, values and staging. Often we only have to think about two stages and can use "type" and "value" as shorthands to name those stages, but maybe there's an opportunity to reduce a lot of compiler/language machinery and do some interesting things here.
Perhaps a type may be known at a later stage, in which case it does have some memory representation (just as types have some representation in memory in a compiler). And also values may have no memory representation when their types terminate staging, as with values of the unit type, values of type '42', quoted expressions, compile-time network connections, etc.
### Flattening
You can always flatten all stages if your type system is rich enough. For example, if you have Op operator in stage 1, and you want to define it in stage 2, you can flatten it in its result, back to stage 1:
Op -> (
// stage 2 stage 1
(Param1 <- @T1, Param2 <- @T2) -> (@Param1 Op @Param2)
)
...
x -> @Op ("t1","t2") // x now holds stage 1 value: ("t1" Op "t2")
That way you can practically define a top type as a type that maps values back to the first stage, piece by piece. Then you don't need a built-in version of top type, and you can call it whatever you want, as it is a type like any other.
### Dangerous
I think (but I'm not sure, because it depends exactly what you are doing), that it is this "flattening" that is causes the paradoxes.
You need to keep the stratification, which means any result must be one stage 'higher' than the arguments. In effect this prevents self-referential definitions. We can be a bit more precise (as done in Datalog) and say that results can be in the same stage as the 'highest' of the two arguments if the result is not negated, and the highest stage + 1 if it is negated.
### Universes and Categories.
Yes, of course you can. My point was more that you can avoid the nesting of universes if you have a concrete model where types cannot be values, and you do not allow types to have types. Types do represent a bunch of values, or perhaps more category theoretically - a bunch of endo functions from a value to itself. If we think of it this way, it is this 'function' that prevents a type actually being represented in memory, because it doesn't exist in the computer at all, but in the intention of the programmer.
### Unit, another try
Product could be defined as an abstraction. Quotient could be defined as an application. In other words, x: a * b * c would be the same as x: a -> b -> c, while x / a / b / c would be the same as x a b c. These examples (if they are appropriate) lead us to forming an expression: y / y that would be considered as *an* unit.
If you would agree with that, unit could be considered as a fully saturated expression (where there is no more space for applying new parameters). Thus, there would be multiple forms of unit, each of them consisted of different, but fully saturated expressions. This would be a point of view on unit from an aspect of openness for accepting new parameters. It aligns with a way of defining natural numbers by an amount of abstraction / application steps (I will write about this soon - an alternative to Church encoding).
Is this definition of unit digestible?
### distinguishing top type from unit type
If we define equality between two notions as equality of expressions that can apply to the notions, then it doesn't matter how we reached unit. It could be x / x, or it could be (x + y) / (x + y), the result of both of them is equal, and that would be unit.
But what happens with 1 / x expressions? If we introduce a rule by which we can divide only by what we have multiplied before, the situation is clear: we can't have that kind of quotient values because the term 1 / x would report a type error (I'm still using a model by which a product is an abstraction and a quotient is an application).
However, we can imagine the following system: until an expression reaches the unit state, we can divide it only by predefined expressions by which we previously multiplied the numerator. When we reach the unit point, we can imagine proceeding to the other side, to completely unbounded quotient values. The dual constraint we would expect would be the dual to that of division: when additionally multiplying quotient values, we can multiply them only by values that are super sets of previous dividing values. Looking at the unit from this aspect, it would behave exactly as top type with some constraints on what can be multiplied by after division.
But, with our new arrangement, equality (and possibly other) comparison would be undecidable because expressions that could be applied to any other expression are not completely constrained, as expectation of new parameters turns into top type after reaching the unit point.
The conclusion is: if we define a product as an abstraction and a quotient as an application, we can not form 1 / x kind of values because equality would be undecidable. The consequence is that we can not equalize the unit type with the top type if we want equality to be decidable.
[Don't confuse type product and quotient with math multiplication and division. Those operations would be defined at higher levels above type product and quotient, while plain product and quotient could be used to represent addition and subtraction, with unit representing zero]
### Negative Unit
Did you know that there exist a "Negative Unit"?
### Negation vs negative
Negative and fractional types are things, but they aren't the things you were asking about. I was originally going to mention them, but decided not to further muddy an already confusing issue.
### DeMorgan
Also, you should not be so quick to conflate the sum data type directly with a logical disjunction. In type (a+b), the choice is exclusive. In (a+a) we need to somehow preserve ordering information. In proposition (a \/ b), it is not exclusive, and order is irrelevant.
Just an intimation.
Logic: ¬(x /\ y) <-> (¬x \/ ¬y)
Types (speculation): ~(x × y) = (~x × y) + (x × ~y) + (~x × ~y)
= (~x + ~y)
Logic: ¬(x \/ y) <-> (¬x /\ ¬y)
Types (speculation): ~(x + y) = (~x × ~y)
Somehow makes sense, but I can't prove or deny it. A consequence of the proof would be that empty product equals complement of empty sum. If the complement of empty sum is any type, we would conclude that unit type equals any type.
### Try using Church-encodings
Try using Church-encodings and Curry-Howard to prove or deny it.
### Negation
What about negation in logic versus negation in types? Curry-Howard correspondence seems not to deal with that.
Ignore, I'm learning about negative and fractional types.
### Negative and fractional types
That's an interesting paper, but it seems like there's a much more obvious correspondence, namely simply that subtraction eliminates alternatives from a sum and that division eliminates projections from a product. Subtraction naturally occurs in case analysis:
match x: X | case y: A => | case z: B => | otherwise => ;; X - A - B | Zero ;; unreachable
Which is equivalent to throwing an exception. E.g in Java there is/was a syntax like:
class Foo {
static int Doit(int arg) throws Fail;
};
Which you can think of as transforming
int => (int + Fail) into int => int by subtracting Fail
Division would seem to correspond to linear projection.
### Projection
May I ask, what do you mean by a projection? Can you show it by an example? And what would be eliminating a projection from Unit?
I have to emphasize that a type product is not necessarily commutative in all instances (example: Cartesian product).
### Projection
https://ncatlab.org/nlab/show/projection
In mainstream programming languages the "dot" operator.
1/X would correspond to a type which will eliminate an X when paired with an X.
### Negative/Fractional types do not work
Note that the paper on negative/fractional types was never published: the denotational semantics turned out to be bogus. The operational semantics still work, but if you're looking at those types for deep insight in to negation, you won't find it.
See here and here.
### A report
I did some homework, and this is what I've found out:
Type operators: abstraction, application, sum and product, could be used as primitive operators in which any other operator can be defined.
Set operators: subset, complement, union and intersect, are a kind of application, sum and inverted sum. Stating that X is an element of a set A is a kind of abstracting X from A. Testing if X is an element of A is testing application of X to A for errors. Complement test is similar to testing if an element is not in some set. As we know, DeMorgan's laws apply to set operations.
Boolean operators are a special case of set operators where we are dealing only with an empty set (false) and non-empty set (true), while each set that is non-empty is considered being equal one to other. Boolean operations, basically being special set operations, also hold on DeMorgan's laws.
Other uses of type operators (like in math, for example) may or may not apply to DeMorgan's laws, depending on specific definitions. Universal negation and reciprocity are still opened questions in my research.
### Negation on types
I have usually seen 'not(T)' interpreted as a continuation accepting a T or 'T -> 0' -- it's a continuation because it never returns a value (which IMHO is a reasonable interpretation of the empty type).
### Negating
I'm using a definition where negating top type yields bottom type, while negating bottom type yields top type. Negating any other type yields top type without negated type.
I define negation as:
Neg => (
(P <- @Any) => (@None @P)
)
As you see, @None type inverts what is applied to it. Applying @Any to P reports an error, while any other value is returned inverted. To recover from an error I use:
... @None => ThisOrThat ...
### Interesting ideas
I can't seem to access your google doc, perhaps you haven't granted public access?
1) is empty sum equal to full sum, equal to Zero? Look in math, what do we get when we sum all the positive and all the negative numbers?
2) is empty product equal to full product, equal to Unit? Again, what would math say about product of all the numbers greater than or less than one?
I think that we have some similar thoughts in the Morgan Stanley hobbes project. We also use a structured type system there, and compile-time induction on product and sum types works as you say (bottoming out in unit for products, void for sums).
For example, a generic 'print' function for records over printable types gets defined like:
class PrintRec r where printRec :: ([char],r) -> ()
instance PrintRec () where printRec _ _ = () instance (r={h*t}, Print h, PrintRec t) => PrintRec r where printRec pfx r = do { putStr(pfx++recordHeadLabel(r)++"="); print(recordHeadValue(r)); printRec(", ", recordTail(r)); }
instance (PrintRec r) => Print r where print r = do { putStr("{ "); printRec("",r); putStr(" }"); }
So if a user types e.g. '{x=1,y=2}' (which has type '{x:int,y:int}') then this definition derives the right function to print it back. And there's a similar way to generically deconstruct variants the same way, terminating in the void type (0).
We also do some things with dynamic grammars, and of course the structure of grammars maps to these "algebraic types" directly.
|
{}
|
Generalised Assignment
Problem definition.
In the Generalized Assignment problem we are given a set of jobs $$J$$ and a set of machines $$M$$. For each job $$j\in J$$ and machine $$i\in M$$ we are given a processing time $$t_{ij}$$ and cost $$c_{ij}$$. For each machine $$i$$ we are also given a maximum time $$T_{i}$$ for which the machine is available. The goal is to assign each job to some machine, so that the total cost is minimized and no machine is used for more than its available time. Both finding the optimal assignment and deciding whether a feasible assignment exists are NP-complete problems.
An LP relaxation of the problem is as follows. We introduce a binary variable $$x_e$$ for every $$e=(i,j)$$ job-machine pair such that $$t_{ij} \leq T_i$$.
\begin{eqnarray*} \mbox{minimize:} & & \\ & \sum_{e=(i,j)} c_e x_e & \\ \mbox{subject to:} & & \\ & \sum_{e\in\delta(j)} x_e = 1 & \mbox{ for every } j\in J\\ & \sum_{e\in\delta(i)} t_e x_e \leq T_i & \mbox{ for every } i\in M\\ & x_e \geq 0 & \mbox{ for every } e\\ \end{eqnarray*}
Solution
We solve the problem using the Shmoys and Tardos approximation iterative rounding algorithm (using the above LP formulation).
Example
#include <iostream>
#include <vector>
int main() {
// sample problem
std::vector<int> machines = {0,1};
std::vector<int> jobs = {0,1};
std::vector<std::vector<int>> cost(2, std::vector<int>(2));
cost[0][0] = 2;
cost[0][1] = 3;
cost[1][0] = 1;
cost[1][1] = 3;
auto costf = [&](int i, int j) { return cost[i][j]; };
std::vector<std::vector<int>> time(2, std::vector<int>(2));
time[0][0] = 2;
time[0][1] = 2;
time[1][0] = 1;
time[1][1] = 1;
auto timef = [&](int i, int j) { return time[i][j]; };
std::vector<int> T = { 2, 2 };
auto Tf = [&](int i) { return T[i]; };
std::vector<std::pair<int, int>> jobs_to_machines;
// solve it
machines.begin(), machines.end(), jobs.begin(), jobs.end(), costf,
timef, Tf, std::back_inserter(jobs_to_machines));
// print result
if (result.first == paal::lp::OPTIMAL) {
for (auto jm : jobs_to_machines) {
std::cout << "Job " << jm.first << " assigned to Machine "
<< jm.second << std::endl;
}
std::cout << "Cost of the solution: " << *(result.second) << std::endl;
} else {
std::cout << "The instance is infeasible" << std::endl;
}
paal::lp::glp::free_env();
return 0;
}
complete example of the usage can be found in file generalised_assignment_example.cpp
Approximation Ratio
The cost of the solution is at most the cost of the optimal solution and each time limit $$T_i$$ is violated at most by a factor of 2.
Complexity
The time complexity of the algorithm is $$O((|J|+|M|)*(|J|*|M|+LP_{time}(|J|*|M|,|J|+|M|)))$$, where $$|J|$$ and $$|M|$$ are respectively the numbers of jobs and machines and $$LP_{time}(col, row)$$ is the time of solving the LP with $$O(col)$$ columns and $$O(row)$$ rows.
The memory complexity of the algorithm is $$O(|J|*|M|+LP_{mem}(|J|*|M|,|J|+|M|))$$, where $$LP_{mem}(col, row)$$ is the memory complexity of solving the LP with $$O(col)$$ columns and $$O(row)$$ rows.
References
The iterative rounding approximation by Shmoys and Tardos is described in [18].
|
{}
|
2.2 Least squared error design of fir filters (Page 13/13)
Page 13 / 13
Section conclusions
This section has derived the four basic ideal lowpass filters: the constant gain passband lowpass filter, the linearly increasing gain passbandlowpass filter, the differentiator with a lowpass filter, and the Hilbert transformer with a lowpass filter. It is shown that each of these can bemodified to allow a spline transition function by a simple weighting function.
Because of using an ${L}_{2}$ approximation error criterion and because of the orthogonality of the basis functions of the Fourier transform, it is shownthat an optimal multiband filter can be built from the linear combination of these optimal building blocks. This new filter design method has theflexibility of the Parks-McClellan algorithm but the simplicity of the windowing methods. It is extremely fast and has no numerical problems.Unlike the windowing methods, the new method allows explicit independent control of multiple transition band edges and gives an optimal design.Its only limitation is not allowing error weighting.
We then derived a second method that likewise allowed multiple pass, stop, and transition bands with arbitrary band edges, but also allowedindependent weighting of each frequency band. There are two limitations on this method. For long filters with wide transition bands with zeroweights and where $N\left({f}_{p}-{f}_{s}\right)>12$ , the equations that must be solved are ill conditioned. This can be partially addressed using optimal splinefunctions with small weights in the transition bands. The second problem is that solving a large number of simultaneous equations can be slow andrequire considerable memory. These problems might be addressed by using special Toeplitz or Toeplitz plus Hankel algorithms [link] or some iterative method.
When should these methods be used? The second method which minimizes the weighted integral squared error should be used anytime the originalproblem dictates a squared error criterion and the product of the length and transition band width is less than twelve, $N\phantom{\rule{0.166667em}{0ex}}\left({f}_{p}-{f}_{s}\right)<12$ . These conditions are often met because the squared error is a measure of thesignal or noise energy and one seldom wants a long filter and a wide transition band. Even though this method requires solution of a set ofsimultaneous equations and is, therefore, slower than the spline transition function method, it executes in a few seconds on a PC orworkstation and allows independent weighting of different frequency bands.
The first method which uses spline functions in the ideal response transition bands will design essentially arbitrarily long filters veryquickly but it will not allow any error weighting. Although artificial transition functions are used in the ideal response, the optimized splinefunctions are very close to the response actually obtained by the second method with zero weighting in the transition band. This means the optimalapproximation to the ideal response with spline functions transition bands is close to that obtained using the second numerical method. Comparisonsof these effects for a single band can be found in [link] . If a Chebyshev approximation is desired, the Parks-McClellan method should beused although it too has numerical problems for long filters with wide transition bands. If different error measures are wanted in differentbands, the iterative reweighted least squares (IRLS) algorithm [link] should be used. Recent research suggest that for many practical signal specifications, a mixture of Chebyshev and least squaresis appropriate with no explicit transition bands [link] .
If the equations that must be solved to obtain the optimal filter coefficients are ill-conditioned, an orthogonalization procedure can beused to improve the conditioning [link] .
Characteristics of optimalFilters
Gibbs phenomenon, transition band, pole-zero plots, etc.
ComplexAnd minimum phase approximation
Here we talk about which methods also solve the complex approximation problem. We talk about the minimum phase filter.
where we get a research paper on Nano chemistry....?
nanopartical of organic/inorganic / physical chemistry , pdf / thesis / review
Ali
what are the products of Nano chemistry?
There are lots of products of nano chemistry... Like nano coatings.....carbon fiber.. And lots of others..
learn
Even nanotechnology is pretty much all about chemistry... Its the chemistry on quantum or atomic level
learn
da
no nanotechnology is also a part of physics and maths it requires angle formulas and some pressure regarding concepts
Bhagvanji
hey
Giriraj
Preparation and Applications of Nanomaterial for Drug Delivery
revolt
da
Application of nanotechnology in medicine
what is variations in raman spectra for nanomaterials
I only see partial conversation and what's the question here!
what about nanotechnology for water purification
please someone correct me if I'm wrong but I think one can use nanoparticles, specially silver nanoparticles for water treatment.
Damian
yes that's correct
Professor
I think
Professor
Nasa has use it in the 60's, copper as water purification in the moon travel.
Alexandre
nanocopper obvius
Alexandre
what is the stm
is there industrial application of fullrenes. What is the method to prepare fullrene on large scale.?
Rafiq
industrial application...? mmm I think on the medical side as drug carrier, but you should go deeper on your research, I may be wrong
Damian
How we are making nano material?
what is a peer
What is meant by 'nano scale'?
What is STMs full form?
LITNING
scanning tunneling microscope
Sahil
how nano science is used for hydrophobicity
Santosh
Do u think that Graphene and Fullrene fiber can be used to make Air Plane body structure the lightest and strongest. Rafiq
Rafiq
what is differents between GO and RGO?
Mahi
what is simplest way to understand the applications of nano robots used to detect the cancer affected cell of human body.? How this robot is carried to required site of body cell.? what will be the carrier material and how can be detected that correct delivery of drug is done Rafiq
Rafiq
if virus is killing to make ARTIFICIAL DNA OF GRAPHENE FOR KILLED THE VIRUS .THIS IS OUR ASSUMPTION
Anam
analytical skills graphene is prepared to kill any type viruses .
Anam
Any one who tell me about Preparation and application of Nanomaterial for drug Delivery
Hafiz
what is Nano technology ?
write examples of Nano molecule?
Bob
The nanotechnology is as new science, to scale nanometric
brayan
nanotechnology is the study, desing, synthesis, manipulation and application of materials and functional systems through control of matter at nanoscale
Damian
Is there any normative that regulates the use of silver nanoparticles?
what king of growth are you checking .?
Renato
What fields keep nano created devices from performing or assimulating ? Magnetic fields ? Are do they assimilate ?
why we need to study biomolecules, molecular biology in nanotechnology?
?
Kyle
yes I'm doing my masters in nanotechnology, we are being studying all these domains as well..
why?
what school?
Kyle
biomolecules are e building blocks of every organics and inorganic materials.
Joe
how did you get the value of 2000N.What calculations are needed to arrive at it
Privacy Information Security Software Version 1.1a
Good
Got questions? Join the online conversation and get instant answers!
|
{}
|
Home
>
English
>
Class 11
>
Chemistry
>
Chapter
>
General Organic Chemistry
>
Consider the Hofmann ammonolys...
Updated On: 27-06-2022
Get Answer to any question, just click a photo and upload the photo and get the answer completely free,
Text Solution
3^@ gt 2^@ gt 1^@ gt NH_3NH_3 gt 1^@ gt 2^@ gt 3^@1^@ gt 2^@ gt NH_3 gt 3^@1^@ gt NH_3 gt 2^@ gt 3^@
Solution : (d) In gaseous or nonpolar solvent, the basic order is 3^@ gt 2^@ gt 1^@ gt NH_3.
Step by step solution by experts to help you in doubt clearance & scoring excellent marks in exams.
Transcript
give one calling Hoffman ammonolysis reaction to convert Ammonia to primary secondary amine and tertiary amine respectively ok question is isopropyl Arif isopropyl then basic of the above a mind in the xpose medium show the medium play in the basis of the indications face basically we can simply assess the beauty of the Mind by simply looking the nature of the alkaloid present over the years medium physical if you want to access the
DC City order to keep actor plays a role in deciding the beach UB City to respected ka the first what happened is the post I am taking the tertiary amine ok Army ok ok so what happened basically it is a of the nitrogen so water cannot easily attached to the lone pair of the nitrogen why it is so it is so because he's able ki group and they will still be a from the water Malik ok if the water is then how it will be a paise basically because it has to combined with the water not to releasing postman and it will act as busy Kali
ok so you can see that it affect the basicity of the compound ok the second factor in solvation determine that how is the ammonium Ion it is sperm after donating the which metal is formed for example this is our rnh2 basically and on reacting with water it from our NH 38 - ok to know if table is this cat and perform more the tendency of the reaction to proceed forward direction and has more West - will be released and more basic solution that's why our solution also plays a major role in
the effect is the interaction effect that we also see indication physically interaction effect that mean for inductive effect inductive effect and affect getting attached to the nitrogen in determine if there + y group physical then what will be the increase in intensity overnight 2 day panel builder in the city of the compound ok so effectively main Jarur in the Act was basically a group that order of basicity will be our 3rd list Paisa due to Intense fall into degree following one degree and NH3
that I made myself clear thanks for watching
|
{}
|
# GP Regression with LOVE for Fast Predictive Variances and Sampling¶
## Overview¶
In this notebook, we demonstrate that LOVE (the method for fast variances and sampling introduced in this paper https://arxiv.org/abs/1803.06058) can significantly reduce the cost of computing predictive distributions. This can be especially useful in settings like small-scale Bayesian optimization, where predictions need to be made at enormous numbers of candidate points.
In this notebook, we will train a KISS-GP model on the skillcraftUCI dataset, and then compare the time required to make predictions with each model.
NOTE: The timing results reported in the paper compare the time required to compute (co)variances only. Because excluding the mean computations from the timing results requires hacking the internals of GPyTorch, the timing results presented in this notebook include the time required to compute predictive means, which are not accelerated by LOVE. Nevertheless, as we will see, LOVE achieves impressive speed-ups.
[1]:
import math
import torch
import gpytorch
import tqdm
from matplotlib import pyplot as plt
# Make plots inline
%matplotlib inline
For this example notebook, we’ll be using the elevators UCI dataset used in the paper. Running the next cell downloads a copy of the dataset that has already been scaled and normalized appropriately. For this notebook, we’ll simply be splitting the data using the first 40% of the data as training and the last 60% as testing.
Note: Running the next cell will attempt to download a small dataset file to the current directory.
[14]:
import urllib.request
import os
from scipy.io import loadmat
from math import floor
# this is for running the notebook in our testing framework
smoke_test = ('CI' in os.environ)
if not smoke_test and not os.path.isfile('../elevators.mat'):
if smoke_test: # this is for running the notebook in our testing framework
X, y = torch.randn(100, 3), torch.randn(100)
else:
X = data[:, :-1]
X = X - X.min(0)[0]
X = 2 * (X / X.max(0)[0]) - 1
y = data[:, -1]
train_n = int(floor(0.8 * len(X)))
train_x = X[:train_n, :].contiguous()
train_y = y[:train_n].contiguous()
test_x = X[train_n:, :].contiguous()
test_y = y[train_n:].contiguous()
if torch.cuda.is_available():
train_x, train_y, test_x, test_y = train_x.cuda(), train_y.cuda(), test_x.cuda(), test_y.cuda()
LOVE can be used with any type of GP model, including exact GPs, multitask models and scalable approximations. Here we demonstrate LOVE in conjunction with KISS-GP, which has the amazing property of producing constant time variances.
## The KISS-GP + LOVE GP Model¶
We now define the GP model. For more details on the use of GP models, see our simpler examples. This model uses a GridInterpolationKernel (SKI) with an Deep RBF base kernel. The forward method passes the input data x through the neural network feature extractor defined above, scales the resulting features to be between 0 and 1, and then calls the kernel.
The Deep RBF kernel (DKL) uses a neural network as an initial feature extractor. In this case, we use a fully connected network with the architecture d -> 1000 -> 500 -> 50 -> 2, as described in the original DKL paper. All of the code below uses standard PyTorch implementations of neural network layers.
[3]:
class LargeFeatureExtractor(torch.nn.Sequential):
def __init__(self, input_dim):
super(LargeFeatureExtractor, self).__init__()
class GPRegressionModel(gpytorch.models.ExactGP):
def __init__(self, train_x, train_y, likelihood):
super(GPRegressionModel, self).__init__(train_x, train_y, likelihood)
self.mean_module = gpytorch.means.ConstantMean()
self.covar_module = gpytorch.kernels.GridInterpolationKernel(
gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel()),
grid_size=100, num_dims=2,
)
# Also add the deep net
self.feature_extractor = LargeFeatureExtractor(input_dim=train_x.size(-1))
def forward(self, x):
# We're first putting our data through a deep net (feature extractor)
# We're also scaling the features so that they're nice values
projected_x = self.feature_extractor(x)
projected_x = projected_x - projected_x.min(0)[0]
projected_x = 2 * (projected_x / projected_x.max(0)[0]) - 1
# The rest of this looks like what we've seen
mean_x = self.mean_module(projected_x)
covar_x = self.covar_module(projected_x)
return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)
likelihood = gpytorch.likelihoods.GaussianLikelihood()
model = GPRegressionModel(train_x, train_y, likelihood)
if torch.cuda.is_available():
model = model.cuda()
likelihood = likelihood.cuda()
### Training the model¶
The cell below trains the GP model, finding optimal hyperparameters using Type-II MLE. We run 20 iterations of training using the Adam optimizer built in to PyTorch. With a decent GPU, this should only take a few seconds.
[5]:
training_iterations = 1 if smoke_test else 20
# Find optimal model hyperparameters
model.train()
likelihood.train()
# Use the adam optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=0.1) # Includes GaussianLikelihood parameters
# "Loss" for GPs - the marginal log likelihood
mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, model)
def train():
iterator = tqdm.notebook.tqdm(range(training_iterations))
for i in iterator:
output = model(train_x)
loss = -mll(output, train_y)
loss.backward()
iterator.set_postfix(loss=loss.item())
optimizer.step()
%time train()
CPU times: user 2.1 s, sys: 136 ms, total: 2.24 s
Wall time: 2.23 s
## Computing predictive variances (KISS-GP or Exact GPs)¶
### Using standard computaitons (without LOVE)¶
The next cell gets the predictive covariance for the test set (and also technically gets the predictive mean, stored in preds.mean) using the standard SKI testing code, with no acceleration or precomputation.
Note: Full predictive covariance matrices (and the computations needed to get them) can be quite memory intensive. Depending on the memory available on your GPU, you may need to reduce the size of the test set for the code below to run. If you run out of memory, try replacing test_x below with something like test_x[:1000] to use the first 1000 test points only, and then restart the notebook.
[6]:
import time
# Set into eval mode
model.eval()
likelihood.eval()
start_time = time.time()
preds = likelihood(model(test_x))
exact_covar = preds.covariance_matrix
exact_covar_time = time.time() - start_time
print(f"Time to compute exact mean + covariances: {exact_covar_time:.2f}s")
Time to compute exact mean + covariances: 1.81s
### Using LOVE¶
Next we compute predictive covariances (and the predictive means) for LOVE, but starting from scratch. That is, we don’t yet have access to the precomputed cache discussed in the paper. This should still be faster than the full covariance computation code above.
To use LOVE, use the context manager with gpytorch.settings.fast_pred_var():
You can also set some of the LOVE settings with context managers as well. For example, gpytorch.settings.max_root_decomposition_size(100) affects the accuracy of the LOVE solves (larger is more accurate, but slower).
In this simple example, we allow a rank 100 root decomposition, although increasing this to rank 20-40 should not affect the timing results substantially.
[7]:
# Clear the cache from the previous computations
model.train()
likelihood.train()
# Set into eval mode
model.eval()
likelihood.eval()
with torch.no_grad(), gpytorch.settings.fast_pred_var(), gpytorch.settings.max_root_decomposition_size(100):
start_time = time.time()
preds = model(test_x)
fast_time_no_cache = time.time() - start_time
The above cell additionally computed the caches required to get fast predictions. From this point onwards, unless we put the model back in training mode, predictions should be extremely fast. The cell below re-runs the above code, but takes full advantage of both the mean cache and the LOVE cache for variances.
[8]:
with torch.no_grad(), gpytorch.settings.fast_pred_var():
start_time = time.time()
preds = likelihood(model(test_x))
fast_covar = preds.covariance_matrix
fast_time_with_cache = time.time() - start_time
[9]:
print('Time to compute mean + covariances (no cache) {:.2f}s'.format(fast_time_no_cache))
print('Time to compute mean + variances (cache): {:.2f}s'.format(fast_time_with_cache))
Time to compute mean + covariances (no cache) 0.32s
Time to compute mean + variances (cache): 0.14s
### Compute Error between Exact and Fast Variances¶
Finally, we compute the mean absolute error between the fast variances computed by LOVE (stored in fast_covar), and the exact variances computed previously.
Note that these tests were run with a root decomposition of rank 10, which is about the minimum you would realistically ever run with. Despite this, the fast variance estimates are quite good. If more accuracy was needed, increasing max_root_decomposition_size would provide even better estimates.
[10]:
mae = ((exact_covar - fast_covar).abs() / exact_covar.abs()).mean()
print(f"MAE between exact covar matrix and fast covar matrix: {mae:.6f}")
MAE between exact covar matrix and fast covar matrix: 0.000657
## Computing posterior samples (KISS-GP only)¶
With KISS-GP models, LOVE can also be used to draw fast posterior samples. (The same does not apply to exact GP models.)
### Drawing samples the standard way (without LOVE)¶
We now draw samples from the posterior distribution. Without LOVE, we accomlish this by performing Cholesky on the posterior covariance matrix. This can be slow for large covariance matrices.
[11]:
import time
num_samples = 20 if smoke_test else 20000
# Set into eval mode
model.eval()
likelihood.eval()
start_time = time.time()
exact_samples = model(test_x).rsample(torch.Size([num_samples]))
exact_sample_time = time.time() - start_time
print(f"Time to compute exact samples: {exact_sample_time:.2f}s")
Time to compute exact samples: 1.92s
### Using LOVE¶
Next we compute posterior samples (and the predictive means) using LOVE. This requires the additional context manager with gpytorch.settings.fast_pred_samples():.
Note that we also need the with gpytorch.settings.fast_pred_var(): flag turned on. Both context managers respond to the gpytorch.settings.max_root_decomposition_size(100) setting.
[12]:
# Clear the cache from the previous computations
model.train()
likelihood.train()
# Set into eval mode
model.eval()
likelihood.eval()
with torch.no_grad(), gpytorch.settings.fast_pred_var(), gpytorch.settings.max_root_decomposition_size(200):
# NEW FLAG FOR SAMPLING
with gpytorch.settings.fast_pred_samples():
start_time = time.time()
_ = model(test_x).rsample(torch.Size([num_samples]))
fast_sample_time_no_cache = time.time() - start_time
# Repeat the timing now that the cache is computed
with gpytorch.settings.fast_pred_samples():
start_time = time.time()
love_samples = model(test_x).rsample(torch.Size([num_samples]))
fast_sample_time_cache = time.time() - start_time
print('Time to compute LOVE samples (no cache) {:.2f}s'.format(fast_sample_time_no_cache))
print('Time to compute LOVE samples (cache) {:.2f}s'.format(fast_sample_time_cache))
Time to compute LOVE samples (no cache) 0.74s
Time to compute LOVE samples (cache) 0.02s
### Compute the empirical covariance matrices¶
Let’s see how well LOVE samples and exact samples recover the true covariance matrix.
[13]:
# Compute exact posterior covar
start_time = time.time()
posterior = model(test_x)
mean, covar = posterior.mean, posterior.covariance_matrix
exact_empirical_covar = ((exact_samples - mean).t() @ (exact_samples - mean)) / num_samples
love_empirical_covar = ((love_samples - mean).t() @ (love_samples - mean)) / num_samples
exact_empirical_error = ((exact_empirical_covar - covar).abs()).mean()
love_empirical_error = ((love_empirical_covar - covar).abs()).mean()
print(f"Empirical covariance MAE (Exact samples): {exact_empirical_error}")
print(f"Empirical covariance MAE (LOVE samples): {love_empirical_error}")
Empirical covariance MAE (Exact samples): 0.0043566287495195866
Empirical covariance MAE (LOVE samples): 0.0061592841520905495
[ ]:
|
{}
|
Home > theory > DP and the Erdős–Rényi model
## DP and the Erdős–Rényi model
Yesterday I was in a pub with Vasilis Syrgkanis and Elisa Celis and we were discussing about how to calculate the expected size of a connected component in $G(n,p)$, the Erdős–Rényi model. $G(n,p)$ is the classical random graph obtained by considering $n$ nodes and adding each edge $(i,j)$ independently with probability $p$. A lot is known about its properties, which very interestingly change qualitatively as the value of $p$ changes relativeto $n$. For example, for $p <\frac{1}{n}$ then there is no component greater than $O(\log n)$ with high probability. When $p = \frac{c}{n}$, $c>1$ and $n \rightarrow \infty$, then the graph has a giant component. All those phenomena are very well studied in the context of probabilistic combinatorics and also in social networks. I remember learning about them in Jon Kleinberg’s Structure of Information Networks class.
So, coming back to our conversation, we were thinking on how to calculate the size of a connected component. Fix some node $u$ in $G(n,p)$ – it doesn’t matter which node, since all nodes are equivalent before we start tossing the random coins. Now, let $C_u$ be the size of the connected component of node $u$. The question is how to calculate $C(n,p) = \mathbb{E} [C_u]$.
Recently I’ve been learning MATLAB (actually, I am learning Octave, but it is the same) and I am very amazed by it and impressed about why I haven’t learned it before. It is a programming language that somehow knows exactly how mathematicians think and the syntax is very intuitive. All the operations that you think of performing when doing mathematics, they have implemented. Not that you can’t do that in C++ or Python, in fact, I’ve been doing that all my life, but in Octave, things are so simple. So, I thought this was a nice opportunity for playing a bit with it.
We can calculate $C(n,p)$ using a dynamic programming algorithm in time $O(n^2)$ – well, maybe we can do it more efficiently, but the DP I thought was the following: let’s calculate $\mathcal{C}(n,s,p)$ where it is the expected size of the $u$-connected component of a random graph with $n$ nodes where the edges between $u$ and other nodes have probability $p' = 1 - (1-p)^s$ and an edge between $v_1$ and $v_2$ have probability $p$. What we want to compute is $C(n,p) = \mathcal{C}(n,1,p)$.
What we can do is to use the Principle of Deferred Decisions, and toss the coins for the $n-1$ edges between $u$ and the other nodes. With probability $bin(k,n,p') = {n \choose k} (p')^k (1-‘p)^{n-k}$, there are $k$ edges between $u$ and the other nodes, say nodes $w_1, \hdots, w_k$. If we collapse those nodes to $u$ we end up with a graph of $n-k$ nodes and the problem is equivalent to $k$ plus the size of the connected component of $u$ in the collapsed graph.
One difference, however is that the probability that the collapsed node $u$ is connected to a node $v$ of the $n-1-k$ nodes is the probability that at least one of $w_i$ is connected to $v$, which is $1-(1-p)^k$. In this way, we can write:
$\mathcal{C}(n,s,p) = 1 \cdot bin(0,n-1,p') + \sum_{k=1}^{n-1} bin(k,n-1,p') [ k + \mathcal{C}(n-k,k,p)]$
where $p' = 1-(1-p)^s$. Now, we can calculate $C(n,p)$ by using DP, simply by filling an $n \times n$ table. In Octave, we can do it this way:
function component = C(N,p)
C_table = zeros(N,N);
for n = 1:N for s =1:N
C_table(n,s) = binopdf(0,n-1,1-((1-p)^s)) ;
for k = 1:n-1
C_table(n,s) += binopdf(k,n-1,1-((1-p)^s)) * (k + C_table(n-k,k));
end
end end
component = C_table(N,1);
endfunction
And in fact we can call $C(n,p)$ for say $n = 200$ and $p = 0.01 .. 0.3$ and see how $C(n,p)$ varies. This allows us, for example, to observe the sharp transition that happens before the giant component is formed. The plot we get is:
# Erdős–Rényi model
Categories: theory Tags:
|
{}
|
# Tutorial problems Analog communications
Pb1. A broadcast radio transmitter radiates 5KW power when the modulation percentage is 60% , how much is the carier power?
pb2. A 400 Watts carrier is modulated to a depth of 75%, calculate the total power in the modulated wave by assuming the modulating wave as sinusoidal signal. .
Pb3. The antenna current of an AM transmitter is 8 A when only carrier is being transmitted , but is increases to 8.96 A , when the carrier is modulated by a single-tone sinusoid, find the percentage of modulation? find the antenna current when the depth of modulation changes to 0.8. .
Pb4. A 300 Watts carrier is simultaneously modulated by two audio waves with modulation percentages of 50 and 60 respectively. what will be the total side band power radiated? .
pb5. Find the power of the signal $V(t)=&space;cos\omega&space;_{c}t&space;+&space;cos\omega&space;_{c}tcos\omega&space;_{m}t$ .
pb6. Find the power of the signal $V(t)=&space;cos\omega&space;_{l}t&space;+&space;cos\omega&space;_{c}tcos\omega&space;_{m}t$ .
|
{}
|
# Can I truncate a CSPRNG psuedorandom number?
This might be too broad to apply for all CSPRNG, but it might apply for the general case, I'm not sure. I need this specifically for python os.urandom() and SystemRandom() which get a seed from /dev/urandom, and on Windows CryptGenRandom(),
Is it possible to truncate or even modify the random number but still retains its randomness. The reason I need to do this is because the OS has nanosleep and the overflowing digits I will need to cut off.
• you want all the numbers to appear with equal probability after truncate? – crypt Jun 17 '17 at 18:42
• @Raza i can understand that, but there exist truncated probability distribution such as truncated exponential dist. to produce random numbers and rejection sampling. While, im no statistician/cryptographer I was wondering if there was anything on similar lines – Anderson Jun 17 '17 at 18:47
• to keep the distribution probability satisfied, you take mod of the number with nearest power(n) to 2 such that desired range of random numbers is less than 2^n. after that if your number is in desired range, you use it, if not, you repeat the process. this way you will get sufficient level of randomness. if you just truncate the result to your desired range, it may loose randomness – crypt Jun 17 '17 at 18:57
• define your new upper range as a 2^n to avoid validating a simple rnd % upper operation. if you end on a non-power-of-2, it's a lot more complicated to assure uniform distro, especially on the "end caps" – dandavis Jun 17 '17 at 19:06
• @dandavis Not that hard, Raza just showed a not very efficient but valid way of doing so for any kind of number. – Maarten Bodewes Jun 17 '17 at 19:43
|
{}
|
## elements of $K_0$ group
Let $e$ be an idempotent in a unital algebra $A$ and $u=\begin{pmatrix}1-e & e\\ e & 1-e\end{pmatrix}$, then $u$ is invertible and $u\begin{pmatrix}1-e & 0\\ 0 & e\end{pmatrix}=\begin{pmatrix}1 & 0\\ 0 & 0\end{pmatrix}u.$ So, $\begin{pmatrix}e & 0\\ 0 & 1-e\end{pmatrix}$ is Murrary-von Neumann equivalent to $\begin{pmatrix}1 & 0\\ 0 & 1\end{pmatrix}$ in $M_2(A)$.
Suppose $g=[e]-[f]$ is an element of a $K_0$ group, then \begin{align*}g=&[e]+[1-f]-[1-f]-[f]=[\begin{pmatrix}e & 0\\ 0 & 1-f\end{pmatrix}]-[\begin{pmatrix}1-f & 0\\ 0 & f\end{pmatrix}]\\=&[\begin{pmatrix}e & 0\\ 0 & 1-f\end{pmatrix}]-[\begin{pmatrix}1 & 0\\ 0 & 0\end{pmatrix}].\end{align*}
|
{}
|
MathSciNet bibliographic data MR717125 (86a:60006) 60B11 (60E07) Jurek, Zbigniew J. The classes \$L\sb{m}(Q)\$$L\sb{m}(Q)$ of probability measures on Banach spaces. Bull. Polish Acad. Sci. Math. 31 (1983), no. 1-2, 51–62. Links to the journal or article are not yet available
For users without a MathSciNet license , Relay Station allows linking from MR numbers in online mathematical literature directly to electronic journals and original articles. Subscribers receive the added value of full MathSciNet reviews.
|
{}
|
# B Particle behavior and the Doppler effect
1. Sep 28, 2018
### itoero
How does particle physics explain the doppler effect? (including blue/red shift)
2. Sep 28, 2018
### Staff: Mentor
Doppler is a wave phenomenon and has no particular connection to particle physics.
3. Sep 29, 2018
### itoero
Yes doppler is only about waves but what happens on a particle level?
In dopplerredshift you measure low energy photons on one side and higher energy photons on the other side.
How can photons just change energy?
4. Sep 29, 2018
### Drakkith
Staff Emeritus
The energy of anything is not invariant. Simply changing reference frames can result in a drastic decrease or increase in the energy of an object or wave. For example, a moving car on a highway has a lot of kinetic energy as viewed from a person standing on the side of the road, but has negligible kinetic energy viewed from another car moving alongside the first.
So then your question would become, "How can a car just change energy?" The answer to which is that part of the energy content of an object or wave is frame dependent. For massless particles like photons, all of its energy is frame dependent, whereas for objects with mass part of their energy content is locked up in their mass and thus forms a 'minimum' energy level that the object can never fall under.
5. Sep 29, 2018
### Mister T
In general, you need collections of large numbers of particles to exhibit wave properties.
There is no change in any one photon's energy. Some are observed to have a high energy and some a low energy, but that difference is due to the observer's relative motion.
6. Oct 3, 2018
### itoero
I don't think that' a valid explanation. You view your own speed due the direct environment (concrete, grass, trees….) the observable speed of the other cars is based on the difference with your speed.
I'm not asking how a car changes energy.
The light emitted from a star is white. Yet we observe blue light on one side and red light on the other. How can photons change energy without inelastic scattering.
Why do you think cosmological redshift is due to the doppler effect? There is a big difference between sound waves and electromagnetic waves.
7. Oct 3, 2018
### Drakkith
Staff Emeritus
No, we just choose to use the Earth as the de facto frame of reference when referring to speed and velocity for most of our everyday lives because it is convenient. However the truth is that in our own frame of reference we simply aren't moving and have no kinetic energy. This is a fundamental principle of physics.
Sure you are. You're asking how a car changes energy because you're asking how a photon changes energy and the two phenomena follow many of the same laws of physics.
The idea that photons have one specific energy is only applicable if you choose to measure from a single frame of reference. If you switch to another the photons may not have the same energy. To put it simply, they don't have a specific energy in general. Energy is conserved, but it is not frame-invariant.
8. Oct 3, 2018
### Mister T
You haven't given an example of a photon changing its energy!
Observers can measure the energy of light. Is it hard for you to accept the notion that the energy observed depends on the motion of the observer relative to the source? One observes a beam of light to be blue while another observes it to be red. The light never changed from blue to red, the only thing that changed is the observer's motion relative to the source.
9. Oct 11, 2018
### Staff: Mentor
What makes you think they changed energy? In the frame where the star’s light is white it remains white and has the same energy on all sides. The red and blue shift is due to the Doppler effect on the detector, not a change in energy of the light.
Energy is frame dependent, so if you want to claim that the energy changed then you need to identify what reference frame you think that happened.
Last edited: Oct 11, 2018
10. Oct 12, 2018
### itoero
Which laws? I don't get why you think that's a valid comparison. A photon always travels at c, regardless the energy it has. A car does not.
[
How do you know which frame of reference to take?
We don't know why motion does that. The doppler is a description of a phenomenon it doesn't explain the phenomenon. Do you deny this?
Why isn't the star taken as frame of reference?
11. Oct 12, 2018
### ZapperZ
Staff Emeritus
I still do not see that you have established the starting point of your entire thread here, i.e. the connection between "particle physics" and "doppler effect". Why do you think particle physics can or should "explain" (whatever that word means) the doppler effect?
Until you can do that, this is similar to asking how particle physics can explain funny.
Zz.
12. Oct 12, 2018
### Mister T
You're free to choose any one you like. There is no wrong or right choice.
Sure we do. The energy of what you observe is dependent on your motion because of the way we define energy.
The Doppler effect is something we observe. It is also something that we can explain.
13. Oct 12, 2018
### Mister T
When a massive object moves at a speed that's nearly $c$ relative to you, this is what you observe. Very very small changes in the object's speed are associated with very very large changes in the object's energy. It is possible to get so close the speed $c$ that when the energy is increased by orders of magnitude there is a negligible increase in speed.
There are people doing this every day at locations all around the world. It's an undisputed fact.
Just what is it you're trying to understand here?
14. Oct 12, 2018
### Drakkith
Staff Emeritus
To take for what?
It can be. There's nothing wrong with that. But since the star is moving with respect to us here on Earth, you will get different measurements for the energy of the starlight if you measure in both frames.
15. Oct 12, 2018
### Staff: Mentor
The Principle of Relativity:
https://en.m.wikipedia.org/wiki/Principle_of_relativity
I'll be succinct: do you understand and accept that the speed and therefore the kinetic energy of a car are frame of reference dependent?
Your responses imply that you don't know what a frame of reference is or is used for.
16. Oct 12, 2018
### Staff: Mentor
It certainly can be, you just have to be clear. In the star’s frame of reference the energy does not change.
I deny it. Not only do we know exactly why motion does that, the derivation is very basic and well known freshman-level physics.
Last edited: Oct 12, 2018
17. Oct 26, 2018
### itoero
Then why motion does that?
18. Oct 26, 2018
### itoero
Yes but what does that matter? The speed of a car does not change for different observers.
19. Oct 26, 2018
### ZapperZ
Staff Emeritus
Yes it does. Different reference frame will measure different speed! That is what "frame dependent" means!
Zz.
20. Oct 26, 2018
### Staff: Mentor
Yep. This is why I said we need to start this walkthrough with these foundational physics concepts before even getting into Doppler shift itself.
So.
What is a reference frame? It's a set of coordinates against which you make measurements. The most common we use every day are coordinate systems centered on Earth (rotating with it) and centered on ourselves.
So, when I say I am driving my car at 10m/s, what reference frame am I measuring it from? What is the car's speed as measured against the other reference frame?
[note: I'm an engineer, not a physicist so my descriptions tend to be less than fully....formal. Some of that is on purpose but not all of it.]
Last edited: Oct 26, 2018
|
{}
|
## Q. 1.11 Lower energy levels for spectral each spectral series? [ENDORSED]
Molly_McMillen_3J
Posts: 9
Joined: Wed Sep 21, 2016 2:57 pm
### Q. 1.11 Lower energy levels for spectral each spectral series?
The question for 1.11 is " In the spectrum of atomic hydrogen, several lines are generally classified together as belonging to a series... What is common to the lines within a series that makes grouping them together logical?"
I understand the answer to the problem that is in the solutions booklet, ie. I know that the Lyman series has the lower energy level n=1 etc. I just didn't really understand the book's explanation of why each series has each specific energy level. So is there a way to figure out the lowest energy level for lines in each series, or are we just supposed to take the information that Lyman series has n=1, Balmer series n=2, etc. to be a given?
Vivian Wang 3J
Posts: 29
Joined: Wed Sep 21, 2016 2:57 pm
Been upvoted: 1 time
### Re: Q. 1.11 Lower energy levels for spectral each spectral series? [ENDORSED]
Each series has a specific energy level because those are the energy levels at either end of the jump producing a particular line in the spectrum.
"For example, in the Lyman series, n is always 1. Electrons are falling to the 1-level to produce lines in the Lyman series. For the Balmer series, n is always 2, because electrons are falling to the 2-level."
I suppose then, that the values are given for each series.
|
{}
|
# includegraphics is missing a number, treating it as zero
Here is the entire code for my document:
\documentclass[11pt]{article}
\usepackage{graphicx}
\begin{document}
\includegraphics{image.pdf}
\end{document}
When compiling, I get the error
! Missing number, treated as zero.
EDIT: Thanks to Marijn for help with formatting.
EDIT 2: Bonus points to whoever can reproduce the phantom character.
What's going on is that there's a phantom character between the { and the i, that's causing the code to not compile. I figured out that the character was there by pasting the code into Overleaf: it displayed the phantom character immediately.
|
{}
|
Now showing items 1-20 of 181384
(2016)
• #### A 1-dimensional statistical mechanics model for nucleosome positioning on genomic DNA
(IOP Science, 2016-02-12)
The first level of folding of DNA in eukaryotes is provided by the so-called "10-nm chromatin fibre", where DNA wraps around histone proteins (~10 nm in size) to form nucleosomes, which go on to create a zig-zagging ...
• #### 10C continued: a deeper radio survey at 15.7 GHz
(Oxford University Press, 2016-02-04)
We present deep 15.7-GHz observations made with the Arcminute Microkelvin Imager Large Array in two fields previously observed as part of the Tenth Cambridge (10C) survey. These observations allow the source counts to be ...
• #### {1124} Deformation Twinning in Commercial Purity Titanium at Room Temperature
(Taylor & Francis, 2015-06-18)
Definitive evidence from both electron back-scattered diffraction and transmission electron microscopy is shown for the existence of 1124 twinning as a rare deformation twinning mode in coarse grained commercial purity ...
• #### 12-inch celestial globe
(Institute of Astronomy Library, 1968)
(2017-12)
• #### $^{17}$O Solid-State NMR Spectroscopy of Functional Oxides for Energy Conversion
(2018-01-26)
The main aim of this thesis is the development of $^{17}$O solid-state nuclear magnetic resonance (NMR) spectroscopic techniques to study the local structure and ion dynamics of functional oxide materials for applications ...
• #### The 1874–1876 volcano-tectonic episode at Askja, North Iceland: Lateral flow revisited
(Wiley on behalf of the American Geophysical Union, 2013-07-29)
The Askja volcanic system, North Iceland, experienced a volcano-tectonic episode between 1874 and 1876, the climax of which was a rhyolitic, phreatoplinian to Plinian eruption at Askja central volcano on 28–29 March 1875. ...
• #### 2'-$\textit{0}$-Methyl-5-hydroxymethylcytidine: A Second Oxidative Derivative of 5-Methylcytidine in RNA
(American Chemical Society, 2017-02-08)
5-Hydroxymethylcytidine (hm$^{5}$C) was recently identified as a direct metabolite of m$^{5}$C in RNA. We investigated the stability of hm$^{5}$C in human cells using bio-isotopologues and LC-MS/HRMS. This has led to the ...
• #### A 2-adic automorphy lifting theorem for unitary groups over CM fields
(Springer, 2016)
We prove a ‘minimal’ type automorphy lifting theorem for 2-adic Galois representations of unitary type, over imaginary CM fields. We use this to improve an automorphy lifting theorem of Kisin for GL_2.
• #### The 2008 Methoni earthquake sequence: the relationship between the earthquake cycle on the subduction interface and coastal uplift in SW Greece
(Oxford University Press, Oxford University Press, 2017-03-01)
Seismological, GPS and historical data suggest that most of the 40 mm yr$^{-1}$ convergence at the Hellenic Subduction Zone is accommodated through aseismic creep, with earthquakes of $\textit{M}$W ≲ 7 rupturing isolated ...
• #### The 2011 eruption of Nabro volcano, Eritrea: perspectives on magmatic processes from melt inclusions
(2018-01-01)
• #### 2D Coherent Charge Transport in Highly Ordered Conducting Polymers Doped by Solid State Diffusion
(Nature Publishing Group, 2016)
Doping is one of the most important methods to control charge carrier concentration in semiconductors. Ideally, the introduction of dopants should not perturb the ordered microstructure of the semiconducting host. In some ...
• #### 2D control of field-driven magnetic bubble movement using Dzyaloshinskii-Moriya interactions
(AIP Publishing, 2015-01-12)
The field-induced asymmetric growth of magnetic bubble domains in Pt/Co/Pt out-of-plane magnetized films with Dzyaloshinskii-Moriya interactions is used to control the lateral displacement of bubbles. We demonstrate experimentally ...
• #### 2D ice from first principles: structures and phase transitions
(APS, 2016-01-13)
Despite relevance to disparate areas such as cloud microphysics and tribology, major gaps in the understanding of the structures and phase transitions of low-dimensional water ice remain. Here, we report a first principles ...
• #### 2H and 27Al Solid-State NMR Study of the Local Environments in Aldoped 2-Line Ferrihydrite, Goethite, and Lepidocrocite
(American Chemical Society, 2015-05-13)
Although substitution of aluminum into iron oxides and oxyhydroxides has been extensively studied, it is difficult to obtain accurate incorporation levels. Assessing the distribution of dopants within these materials has ...
• #### 2′-Alkynylnucleotides: A Sequence- and Spin Label-Flexible Strategy for EPR Spectroscopy in DNA
(2016-07-27)
• #### A 3-D in vitro co-culture model of mammary gland involution
(Royal Society of Chemistry, 2014-04-02)
Involution is a process whereby the mammary gland undergoes extensive tissue remodelling involving exquisitely coordinated cell death, extracellular matrix degradation and adipose tissue regeneration following the weaning ...
• #### 3-D model simulations of dynamical and microphysical interactions in pyroconvective clouds under idealized conditions
(Copernicus Publishing, 2014-07-29)
Dynamical and microphysical processes in pyroconvective clouds in mid-latitude conditions are investigated using idealized three-dimensional simulations with the Active Tracer High resolution Atmospheric Model (ATHAM). A ...
• #### 3-inch refractor telescope
(Institute of Astronomy Library, 1900)
|
{}
|
# How to estimate stability and stiffness of a system of coupled ODEs?
I'm running into issues with Python/Julia ODE solvers requiring prohibitively small timesteps to evolve a system of 4 coupled ODEs (the order of magnitude of the state variables and time unit span ~40-50 orders of magnitude). Interestingly if I use a simple explicit Euler approach then I can get past the stiffness at early times (where the general adaptive solvers get stuck) and roughly match theoretical expectations at later times.
Apart from the technical coding details, I have noticed that it is common to talk about the mathematical stability and stiffness of ODE systems. Is there a standard way to calculate the expected stability and stiffness given a set of coupled ODEs, initial conditions, integration timescales, input parameters, and maybe a solver algorithm?
For what it's worth, my system of 4 coupled ODEs looks like
$$\frac{dM_1}{dt} = g(t) - c(t,M_1,E)M_1(t) + w(t)M_3(t) - e(M_1,E)h(M_1,E)E(t)$$
$$\frac{dM_2}{dt} = c(t,M_1,E)M_1(t) - s(t)M_2(t) - w(t)M_3(t)$$
$$\frac{dM_3}{dt} = s(t)M_2(t)$$
$$\frac{dE}{dt} = g(t)v(t) - c(t,M_1,E)E(t) + b(t)w(t)M_3(t) - h(M_1,E)E(t)$$
where the various lettered functions are input parameters that depend on time and/or state variables. I know this isn't enough for doing stability/stiffness analysis but it's a start. I'd appreciate any pedagogical references, even for much simpler illustrative systems -- I vaguely remember this involves linear algebra and eigendecomposition but it's been so long since undergrad.
• Have you computed the eigenvalues of the Jacobian of the right hand side? Mar 30 at 15:13
• No but I would love to explore that idea further for different assumptions about the input parameters. Does that need to be done manually or is there a standard package in scipy that can return the Jacobian given a set of ODEs (or matrix of the RHS)? Can you please point me to any simple pedagogical python examples? Mar 30 at 16:24
• I don't know scipy, so can't help. Mar 30 at 16:49
• You could use sympy to describe the RHS and the Jacobian symbolically, then use the function sympy.lambdify to generate python code that evaluates them and produces numpy arrays, and finally call numpy.linalg.eig. Mar 30 at 19:06
|
{}
|
## memoize.lua
kikito
Inner party member
Posts: 3152
Joined: Sat Oct 03, 2009 5:22 pm
Contact:
### memoize.lua
Hi there!
I have implemented a small utility function that some of you might find useful.
It transforms any regular function into a memoized one.
In Programming in Lua there's a simple implementation of function memoization, but it presents several problems:
• It relies on tostring to generate a "string key" for each cached result. This is bound to handle some inputs problematically.
• It doesn't handle functions returning multiple values
• That solution is tied to a particular problem. My implementation is generic.
A quick example that I hope you will all understand:
Code: Select all
local memoize = require 'memoize'
love.graphics.newFont = memoize(love.graphics.newFont)
font1 = love.graphics.newFont(13)
...
font2 = love.graphics.newFont(13) --> A-HA!
The second time love.graphics.newFont is called, it will "remember" that the font that was already created, and just return it; It will not create a new font.
In other words, this function can be used to create "cached versions" of regular functions; functions that that will "remember" the results of previous calls just by looking at the parameter list, and just return the values without performing any calculations.
There are lots of applications - in addition to the resource-loading functions shown above, it can be useful in procedural generation functions (remembering random values), recursive functions, or just plain slow ones.
You might not need this function today. Maybe not tomorrow. But some day, you will need to cache results. On that day, memoize.lua will be there for you.
It is available on this location:
https://github.com/kikito/memoize.lua
I shall now retire to my lair! Bwahahahaa!
Last edited by kikito on Wed Apr 20, 2011 11:18 pm, edited 2 times in total.
When I write def I mean function.
sharpobject
Prole
Posts: 44
Joined: Fri Mar 18, 2011 2:32 pm
Location: California
Contact:
### Re: memoize.lua
Cool, can you post it?
kikito
Inner party member
Posts: 3152
Joined: Sat Oct 03, 2009 5:22 pm
Contact:
### Re: memoize.lua
I've edited my previous post and added the url for the lib. Thank you!
When I write def I mean function.
Taehl
Dreaming in associative arrays
Posts: 1024
Joined: Mon Jan 11, 2010 5:07 am
Location: CA, USA
Contact:
### Re: memoize.lua
I don't need it yet, but it looks pretty sweet. Let me guess, it does fancy things with metatables?
Earliest Love2D supporter who can't Love anymore. Let me disable pixel shaders if I don't use them, dammit!
Lenovo Thinkpad X60 Tablet, built like a tank. But not fancy enough for Love2D 0.10.0+.
sharpobject
Prole
Posts: 44
Joined: Fri Mar 18, 2011 2:32 pm
Location: California
Contact:
### Re: memoize.lua
Taehl wrote:I don't need it yet, but it looks pretty sweet. Let me guess, it does fancy things with metatables?
It looks like it just stores a private cache and uses a function decorator to check the cache. Then it returns the cached value or the return value of the function you gave it.
kikito
Inner party member
Posts: 3152
Joined: Sat Oct 03, 2009 5:22 pm
Contact:
### Re: memoize.lua
sharpobject wrote:
Taehl wrote:I don't need it yet, but it looks pretty sweet. Let me guess, it does fancy things with metatables?
It looks like it just stores a private cache and uses a function decorator to check the cache. Then it returns the cached value or the return value of the function you gave it.
Sharpobject's right on the money. That's precisely what it does.
When I write def I mean function.
BlackBulletIV
Inner party member
Posts: 1260
Joined: Wed Dec 29, 2010 8:19 pm
Location: Queensland, Australia
Contact:
### Re: memoize.lua
Looks great kikito! Don't need it right now, but as you say, it'll be there if I do.
vrld
Party member
Posts: 917
Joined: Sun Apr 04, 2010 9:14 pm
Location: Germany
Contact:
### Re: memoize.lua
Very neat. I like that it handles multiple arguments.
I have come here to chew bubblegum and kick ass... and I'm all out of bubblegum.
hump | HC | SUIT | moonshine
ishkabible
Party member
Posts: 241
Joined: Sat Oct 23, 2010 7:34 pm
Location: Kansas USA
### Re: memoize.lua
do you store the return values in a table and unpack it to return it? that's the only way i can think to do it.
BlackBulletIV
Inner party member
Posts: 1260
Joined: Wed Dec 29, 2010 8:19 pm
Location: Queensland, Australia
Contact:
### Re: memoize.lua
ishkabible wrote:do you store the return values in a table and unpack it to return it? that's the only way i can think to do it.
That's indeed the way it's done. See lines 69, 56, and 72.
### Who is online
Users browsing this forum: No registered users and 3 guests
|
{}
|
Pinned toot
Sometimes I wonder if almost all the problems in the world could be fixed by:
Not considering people themselves as having different values/worths than each other.
Even in lowkey ways! Like making a statement by putting someone down instead of refuting their ideas, or at worst, saying they believe in terrible things.
Pinned toot
Sometimes I feel like writing some fediverse software :3
But it'd be a desktop app and in Java and I worry people would rather I never even wrote it X'D
Pinned toot
I'm the person who'll follow you around like a puppy if I like you, and who spends their alone time playing with and creating all kinds of sciencey mathey computerey things :D
(Maybe I can follow someone around spending time with them *and* do sciencey things! :D )
(Although I'm really busy now in my life with certain projects :( )
(..Maybe someone would like to work on those same projects! :D )
(But I'd have to trust them a lot, and most aren't ready yet as of writing :P )
Pinned toot
(fyi, if I unfollow you it's probably because I start to feel like my presence makes / would make you uncomfortable (or maybe in rare cases, that we just mutually wouldn't get along), not because there's anything wrong with you!)
Pinned toot
by the way people of the world, if I'm annoying and uncomfortable and you wish I'd unfollow you, PLEASE just let me know!! I'm *terrible* at social cues! ><
(I often just delete accounts or don't make them because of how many people I make uncomfortable with my presence, but I'm giving this a shot! if people tell me when I am, then maybe I can avoid causing discomfort enough that I don't have to delete the whole account to prevent incidents I never recognize are making someone uncomfortable!)
Puppy Pi boosted
These pictures of Jupiter taken by the Juno spacecraft are fucking with my emotions; I remember avidly staring at grainy black and white photos of the planets when I was very little. Absolutely breathtaking #astronomy
Puppy Pi boosted
(looks at my own jokes) hehe nice
Puppy Pi boosted
If anyone has tips on how I could get mathjax to work with pleroma-fe I'm all ears
(Answer: CO2 counts for biochemistry and hydrocarbons don't, and both count for topochemistry, ableit with CO2 as a degenerate form to oxalate etc. like CH4 is to ethane etc., and there is no "organic chemistry" to make people think it's free of GMO's :> )
XD
Petition to replace "organic chemistry" with "topochemistry" since what it's really about these days isn't things-that-have-to-do-with-life, but chemistry-that-takes-graph-theory-to-do-right XD
:D
(Then we can stop arguing about whether hydrocarbons and CO2 count or not XD )
Puppy Pi boosted
Puppy Pi boosted
*slaps roof of a russian nesting doll*
this bad boy can fit so many
*sʟᴀᴘs ʀᴏᴏғ ᴏғ ᴀ ʀᴜssɪᴀɴ ɴᴇsᴛɪɴɢ ᴅᴏʟʟ*
ᴛʜɪs ʙᴀᴅ ʙᴏʏ ᴄᴀɴ ғɪᴛ sᴏ ᴍᴀɴʏ
*ˢˡᵃᵖˢ ʳᵒᵒᶠ ᵒᶠ ᵃ ʳᵘˢˢᶦᵃⁿ ⁿᵉˢᵗᶦⁿᵍ ᵈᵒˡˡ*
ᵗʰᶦˢ ᵇᵃᵈ ᵇᵒʸ ᶜᵃⁿ ᶠᶦᵗ ˢᵒ ᵐᵃⁿʸ
Puppy Pi boosted
You catgirl is back home from the super market!
I've returned with lots of kitty chow OwO !!
Good morning everyone!
Puppy Pi boosted
Actually for realz running around liking posts on two accounts because your posts are just so good
Puppy Pi boosted
In 1947 Bell Labs invented the transistor. This has made a lot of people very angry and been widely regarded as a bad move.
Puppy Pi boosted
@codepuppy That's pretty close to a video game I developed in a dream called "Nuclear Death Ball." I still intend to make this game (it's not that complex of a dynamic). All things, in time.
Metamorphic rocks,
Also known as twice-baked rocks.
send toot ^,^
<very obscure post>
Bring back Dr. Kiki's Science Hour! /:'D/
(If the Kiki still wants to ofc :3 )
Puppy Pi boosted
Honestly even favourites help a little bit, as little "I saw this" indicators. I know it feels weird to favourite negative mental health and panic posts but if you don't have the energy for a reply, it helps.
Puppy Pi boosted
If I'm breaking down and panicking and freaking out, please please please don't be afraid to reach out and even just acknowledge me.
It might not visibly help, it might not make me feel better, but as long as it's not completely dismissive I guarantee it will help stop me spiralling and getting worse.
Puppy Pi boosted
The sky is pretty
Puppy Pi boosted
I cant wait till my programming socks get here
Puppy Pi boosted
A Mastodon instance for maths people. The kind of people who make $\pi z^2 \times a$ jokes.
Use $ and $ for inline LaTeX, and $ and $ for display mode.
|
{}
|
## saljudieh07 A particle of mass m moving in 3 dimensions under the potential energy function.... 2 years ago 2 years ago
1. saljudieh07
Rest of Question: A particle of mass m moving in 3 dimensions under the potential energy function $V(x,y,z)=\alpha x+\beta y^2+ \gamma z^3$ has speed Vnaught when it passes through the origin. a) what will its speed be if and when it passes through the point (1,1,1)?
2. saljudieh07
This is what I have done so far: F=-gradient (dot) potential energy function $= - (\alpha i +2y \beta j + 3z^2\gamma k )$ and I make the expression above equal to= mdv/dt but now i am study, when i break down the dv/dt into 3 dimensions how do I integrate both sides with respect to x, y, and z?
3. saljudieh07
Junkiejim to the rescue!!!!!!!!!!!!
4. JunkieJim
okay, having F you should be able to do this: $\textbf{F}=m \frac{\delta \textbf{v}}{\delta t}$$\textbf{F} \delta t = m \delta \textbf{v}$$\int\textbf{F}\delta t = \int m \delta \textbf{v}$ and you integrate each component of F with respect to t, the right side just becomes mv.
5. saljudieh07
yeh but that is force with respect to time, i need force with respect to position that is the problem! coz if you read a, it gives me a value of (1,1,1)
6. JunkieJim
oh, i see your issue, you want to not use force then, I think you should be using conservation of energy.
7. saljudieh07
yeh, i have the force equation, i can make it equal to m (dv/dx dx/dt) if i break dv/dt, then i get mv dv/dx, and i can find the equation of velocity wrt to position, but the problem is, this question is three dimensional not only wrt x... so would it be F= mv (dv/dx +dv/dy + dv/dz)?
8. shubham
OR Considering the system to be closed and forces to be conservative, you can deduce that sum of KE and PE would be constant. We know, KE+PE at origin = KE + PE at (1,1,1) 1/2*m*Vo^2 + 0 = 1/2*m*V(1,1,1) ^2 + alpha+beta+gamma Hence, you can calculate V(1,1,1)
9. shubham
V(1,1,1)=$\sqrt{2(m*Vo^2 /2 - \alpha-\beta-\gamma)/m}$
10. saljudieh07
when you say 1/2*m*Vo^2 + 0 = 1/2*m*V(1,1,1) ^2 + alpha+beta+gamma 1/2*m*V(1,1,1) ^2 << that V is the velocity with respect to position, and position is in terms of x, y, and z, so how do i find that equation, this is what i am struggling with....
11. saljudieh07
does what i am saying makes sense? coz kenetic = 0.5m(velocity)^2
12. JunkieJim
you can split up your dv/dt derivative to look like this: $\frac{dv}{dx}\frac{dx}{dt}\hat i+\frac{dv}{dy}\frac{dy}{dt}\hat j+\frac{dv}{dz}\frac{dz}{dt}\hat k$
13. saljudieh07
so then i will have: let us say this is the expression you wrote (dvdxdxdtiˆ+dvdydydtjˆ+dvdzdzdtkˆ ) would be equal to = -1/m (Force) where the force is: =−(αi+2yβj+3z2γk) but i still don't know how to solve that integral lol..
14. saljudieh07
however, is the idea right?
15. JunkieJim
I think so, when you integrate you should have a line integral, looks something like this $\int\textbf {F} ~\textbf{dl} = \int mv dv$ $\text{where}~~ \textbf{dl}= dx\hat i +dy \hat j +dz\hat k$
16. saljudieh07
hmmm, i see... iight thanks a lot man, if i only could give u more than one star i would of haha.. but yeh.. anyways, amma go sleep on this, when i wake up 2morrow am sure something good will come up with me, if not i will come back 2morrow. thanks guys!
|
{}
|
Research article| Volume 6, ISSUE 8, e04417, August 2020
• PDF [800 KB]PDF [800 KB]
• Top
# A data science approach to 138 years of congressional speeches
Open AccessPublished:August 15, 2020
## Abstract
The availability of automatic data analysis tools and large databases have enabled new ways of studying language and communication that were not possible in the pre-information era. Here we apply a quantitative analysis to a large dataset of USA congressional speeches made over a period of 138 years. The analysis reveals that the readability index of congressional speeches increased consistently until the 96th congress, and then started to decline. Congressional speeches have also become more positive over time, and in general express more sentiments compared to speeches made in the 19th century or early 20th century. The analysis also shows statistically significant differences between Democratic and Republican congressional speeches.
## 1. Introduction
Speeches have been a primary methods of communication in politics and public administration, and their pivotal role in the government and Democratic process has been noted since the ancient Greek and Roman government systems (
• Champion C.
Romans as BAPBAPOI: three polybian speeches and the politics of cultural indeterminacy.
;
• Pepe C.
The Genres of Rhetorical Speeches in Greek and Roman Antiquity.
;
Politics, speech, and the art of persuasion: toward an aristotelian conception of the public sphere.
;
• Fantham E.
The contexts and occasions of roman public rhetoric.
). As these speeches reflect the agenda of the speaker, analysis of the speeches can provide important insights about the way the speaker use language to communicate their views (
• Dowding K.
• Hindmoor A.
• Iles R.
• John P.
Policy agendas in australian politics: the governor-general's speeches, 1945–2008.
;
• Eshbaugh-Soha M.
The politics of presidential speeches.
;
• Schaffner C.
Political speeches and discourse analysis.
;
• Boromisza-Habashi D.
How are political concepts ‘essentially’ contested?.
;
• Remer G.
Genres of political speech: oratory and conversation, today and in antiquity.
). The information era enables the digitization of archives, making very large databases accessible to large-scale manual and machine analysis of the data. That introduces a new approach to the use of language analysis that can reveal insights about political communication that are difficult to identify manually (
Cardie, C., Wilkerson, J., 2008. Text annotation for political science research.
;
• Grimmer J.
• Stewart B.M.
Text as data: the promise and pitfalls of automatic content analysis methods for political texts.
;
• Wilkerson J.
• Casas A.
Large-scale computerized text analysis in political science: opportunities and challenges.
).
Converting transcripts of political speeches into numbers can help identify differences and trends in the language used in the speeches that are impractical to detect in large databases by manual inspection of the text (
• Grimmer J.
• Stewart B.M.
Text as data: the promise and pitfalls of automatic content analysis methods for political texts.
). It is clear that such quantitative analysis cannot capture all information, as machine analysis of text has not yet elevated to the analysis power of the human brain. Namely, computer analysis cannot yet fully “understand” the content and context of the speech or define its political meaning. However, machine analysis can reduce the speeches to text elements that can be measured, and therefore allows quantitative analysis and statistical inference of the speeches.
Substantial work has been done in the application of discourse analysis to political communication (
• Mahdiyan M.
• Rahbar M.
• Hosseini-Maasoum S.M.
Applying critical discourse analysis in translation of political speeches and interviews.
;
Pragmatic features of political speeches in english by some prominent nigerian leaders.
;
• Bonikowski B.
• Gidron N.
The populist style in american politics: presidential campaign discourse, 1952–1996.
;
• Reyes A.
Building intimacy through linguistic choices, text structure and voices in political discourse.
). Natural language processing techniques have also been used to determine ideology proportion in political speeches (
• Sim Y.
• Acree B.D.
• Gross J.H.
• Smith N.A.
Measuring ideological proportions in political speeches.
), and multi-modal methods that combine text analysis with automatic eye tracking provided additional information to the analysis of the text alone (
• Scherer S.
• Layher G.
• Kane J.
• Neumann H.
• Campbell N.
An audiovisual political speech analysis incorporating eye-tracking and perception data.
). It has also been shown that a political position can be identified automatically from the speech transcript (
• Laver M.
• Benoit K.
• Garry J.
Extracting policy positions from political texts using words as data.
). Frequency of certain terms and words has also been used to show similarities and differences between politicians, and can be measured directly through their speeches (
• Savoy J.
Lexical analysis of us political speeches.
), or indirectly through social media and other content related to the politicians (
• Chung C.J.
• Park H.W.
Textual analysis of a political message: the inaugural addresses of two korean presidents.
). Analysis of political speeches was also applied to identify gender-related language differences in parliamentary speeches (
• Sensales G.
• Areni A.
• Giuliano L.
Pronouns and verbs as gender markers in italian parliamentary speeches: intersecting gender, communication, and politics.
).
The US Congressional Record is one of the longest spanning and most significant collections of political documents available. Examining this set of speeches has the potential to yield useful information about historical trends in legislative priorities, speech patterns, and other features of debate and political communication in congress. As discussed above, making such discoveries manually is difficult due to the large size of the data.
Previous approaches to analyzing trends in the US Congressional Record using automation have focused on features designed specifically for legislative speeches.
• Quinn K.M.
• Monroe B.L.
• Colaresi M.
• Crespin M.H.
An automated method of topic-coding legislative speech over time with application to the 105th-108th US senate.
examined the probability of speeches to be related to a given legislative topic between 1997 and 2005. Their analysis provided clear descriptions of the length of debate on various issues (
• Quinn K.M.
• Monroe B.L.
• Colaresi M.
• Crespin M.H.
How to analyze political attention with minimal assumptions and costs.
). Another method of analysis sought to measure changes in partisanship over time based on the association bigrams with a political party (
• Gentzkow M.
• Shapiro J.M.
Measuring group differences in high-dimensional choices: method and application to congressional speech.
). The study determined that partisanship remained stable from 1873 until 1994, after which an increase in partisanship of congressional speeches was identified (
• Gentzkow M.
• Shapiro J.M.
Measuring group differences in high-dimensional choices: method and application to congressional speech.
).
• Yu B.
Language and gender in congressional speech.
used computational methods to show gender differences between congressional speeches of male and female legislators between the years of 1989 and 2008. Analysis of the frequency of congressional speeches in the 103rd (1993-1994) and 109th (2005-2006) congresses showed that female legislators speak at higher rate than male legislators (
• Pearson K.
• Dancey L.
Elevating women's voices in congress: speech participation in the house of representatives.
).
• Yu B.
• Kaufmann S.
• Diermeier D.
Classifying party affiliation from political speech.
used automatic document classification to identify the party of the speech automatically, and identified changes of the speeches across different years, reflected through changes in the classification accuracy of speeches based on the time difference between the training and test data.
• Diermeier D.
• Godbout J.F.
• Yu B.
• Kaufmann S.
Language and ideology in congress.
used a support vector machine (SVM) classifier to identify terms that distinguish between liberal and conservative speeches in the 101st to 108th congresses.
• Thomas M.
• Pang B.
• Lee L.
Get out the vote: determining support or opposition from congressional floor-debate transcripts.
used automatic text classification to identify automatically whether a speech supports or opposes its relevant bill.
Here we applied quantitative text analysis to examine changes in congressional speeches over 138 years. The approach is based on multiple text measurements computed from each speech, and averaged in each year to obtain statistical signal reflecting the trends of these measurements.
## 2. Data
The initial dataset used in this study is a corpus of nearly $1.9⋅106$ congressional speeches made between 1873 and 2010, retrieved from the Congressional Record. Clearly, many of these speeches were made prior to the information era, and when no digital storage devices were available. The speeches were therefore digitized by applying Optical Character Recognition (OCR) to the records provided by HeinOnline (
• Gentzkow M.
• Shapiro J.
Congressional record for the 43rd-114th congresses: parsed speeches and phrase counts.
). The data used in this study is the subset parsed from the bound editions of the Record, which currently spans from the 43rd (1873) through the 111th (2010) congress. The dataset also contained many transcripts of short comments that were not political speeches. An example of such comment is “Mr. Chairman, how much time do we have remaining?”. Another example is “Mr. Speaker, I demand a recorded vote”. Clearly, these are comments that do not express a political view, and therefore cannot be analyzed as speeches. To exclude such comments, text files that contained less than 1000 characters were not included in the dataset. After the exclusion of short comments, the dataset contained 959,237 text files such that each text file is a single congressional speech.
The number of speeches in each year can be different, and the speeches are not equally distributed. Fig. 1 shows the number of speeches in different decades. As the figure shows, the number of speeches generally increases in time.
## 3. Text analysis
Analyzing data at the scales described in Section 2 cannot be done manually, and require automation. For that purpose, the open source UDAT text analysis software (
• Shamir L.
Compound quantitative analysis of text using machine learning.
) was used. UDAT computes multiple different aspects of the text, providing a comprehensive numerical analysis of large text datasets. Unlike some document classifiers, UDAT does not rely solely on the frequency of certain keywords appearing in the text, but also on elements that reflect the structure and writing style (
• Shamir L.
• Diamond D.
• Wallin J.
Leveraging pattern recognition consistency estimation for crowdsourcing data analysis.
;
• Alluqmani A.
• Shamir L.
Writing styles in different scientific disciplines: a data science approach.
). These text elements are quantified to show differences between the different classes of the text data.
To analyze and compare the speeches, several quantifiable text descriptors were extracted from each speech:
1. Coleman–Liau readability index: The purpose of the Coleman–Liau readability index (
• Coleman M.
• Liau T.L.
A computer readability formula designed for machine scoring.
) is to estimate the reading level of the text, and associate the text with a grade. For instance, a Coleman–Liau readability index of 3 means that the text is estimated to be at a reading level suitable for a third grade student. The index is computed by $0.0588⋅100⋅wc+0.296⋅100⋅sw−15.8$, where w is the number of words in the text, c is the number of characters in the text, and s is the number of sentences.
2. Word diversity: Word diversity is determined by $Ww$, where w is the total number of words in the speech, and W is the size of the vocabulary of the speech (total number of unique words). If the same word appears in the text more than once, every appearance of the word after its first appearance in the text will increment w but will not affect W. If no word appears in the text more than once, the number of unique words is equal to the total number of words, and therefore the word diversity of the text is 1, which is the maximum possible value. The words are stemmed using CoreNLP (
• Manning C.
• Surdeanu M.
• Bauer J.
• Finkel J.
• Bethard S.
• McClosky D.
The Stanford CoreNLP natural language processing toolkit.
) to correct for different forms of the same word.
3. Word homogeneity: The word homogeneity measures the change in the frequency of words throughout the speech. The text file of the speech is separated into 10 equal-sized segments, and the homogeneity $hi$ of word i is determined by $hi=max(Fi)−min(Fi)$, where $Fi$ is a set of the frequencies of the word i in the each of the text segments. Words that have frequency of less than 0.001 are ignored to avoid the impact of rarely used words. The homogeneity is then determined by the mean $hi$. The word homogeneity is measured with an inverse scale. If the same words are used consistently throughout the text the word homogeneity is expected to be relatively low, while if a different set of words is used in different parts of the speech the word homogeneity is expected to be high.
4. Total number of words: The total number of words is a measurement of the length of the speech.
5. Sentiments: The sentiment expressed in each sentence in each speech was estimated using CoreNLP (
• Manning C.
• Surdeanu M.
• Bauer J.
• Finkel J.
• Bethard S.
• McClosky D.
The Stanford CoreNLP natural language processing toolkit.
), such that each sentence is assigned with a sentiment value between 0 through 4. Sentiment of 0 means very negative, 1 is negative, 2 is neutral, 3 is positive, and 4 is very positive. The sentiment of each sentence is computed by using the 215,154 labeled phrases and a parse tree of 11,855 sentence combinations, and the text is analyzed with a deep recurrent neural tensor network (
• Socher R.
• Perelygin A.
• Wu J.
• Chuang J.
• Manning C.D.
• Ng A.
• Potts C.
Recursive deep models for semantic compositionality over a sentiment treebank.
). The sentiment tree bank can be found in the CoreNLP website.
6. Topic words: The frequency of words related to certain topics. The frequency of topic words is measured by the number of words associated with the topic divided by the total number of words of the text file. The topics are sports, mathematics, science, states, shapes, school, positive words, negative words, languages, elections, food, money, driving, military, law, countries, dance, emotions, boats, energy, family, music, land, art, astronomy, colors, animals, dog breeds, cat breeds, fish, birds, reptiles, cars, beach, weather, fall, spring, summer, winter, vacation, farm, medicine, trees, transportation, times, clothing, shoes, hats, buildings, birthday, monsters, office, tools, camping, castles, fruits, circus, cooking, geography, kitchen, jobs, leaders, house, restaurants, roads, rocks, weapons, containers, acquaintances, yard, flowers, self, female, male. The topic words are taken from the Enhanced Learning thesaurus. CoreNLP is used to identify the words by their stems, so that different forms of the same word are not counted as different words.
The analysis was done such that the feature values were averaged for each year, and the standard deviation and standard error were determined. In addition to the mean and standard deviation of all speeches made in each year, the features were also computed for the Democratic and Republican speeches separately, to identify possible patterns of differences between parties. More information and access to the software and source code used in this paper can be found in (
• Shamir L.
Compound quantitative analysis of text using machine learning.
).
## 4. Results
The results show substantial differences between speeches in different years. Some of the differences were natural to the wide span of years examined in this study. For instance, the use of words related to computers and the Internet were extremely low in speeches made in the 19th century, as these terms did not exist at the time, or had different meaning (e.g., the word ‘’computer”) that was less of a political concern during that time. Other differences can be directly linked to the political situation of the time. For instance, Fig. 2 shows the frequency of words and terms related to energy (e.g., “oil”, “gas”, “electric”, etc.) in congressional speeches.
As the graph shows, the frequency of energy-related words in congressional speeches has been increasing gradually since 1873. A spike in the frequency of energy terms can be identified around the year of 1973, and can be linked to the Organization of Arab Petroleum Exporting Countries (OAPEC) embargo, naturally attracting the attention of the legislators during that time. Another increase in the frequency of energy terms is noticed in 2008, when gas prices soared. Interestingly, during the OAPEC embargo Democrats used energy terms more frequently than Republicans, while in 2008 Republicans mentioned energy in their speeches more frequently than their Democrat colleagues.
Fig. 3 shows the change in frequency in words that identify women such as “she”, “her”, “hers”, etc., as well as equivalent words that identify men. The figure clearly shows a sharp increase in the use of words that identify women starting the 1980s. The frequency of words that identify men has been decreasing, until reaching almost the same level as the frequency of words that identify women.
The data also show that in the years of 2000-2010 Democratic speeches used more words that identify women compared to Republican speeches. Table 1 shows the mean frequency of women identity words in the 2000s and in the 1870s. The table shows that in the 1870s the frequency of women term was very low, and nearly equal between the different parties. In the 2000s, words related to women identity are more than five times more frequent than in the 1870s, and there are also differences between the frequency of such words in Democratic and Republican speeches.
Table 1Frequency of words that identify women in Democratic and Republican speeches during the 2000s and the 1870s.
2000s0.002954±3 ⋅ 10−50.002525±3 ⋅ 10−5<10−5
1870s0.000537±2 ⋅ 10−50.000514±2 ⋅ 10−50.41
t-test P<10−5<10−5
Fig. 4 shows the change in the Coleman-Liau readability index. The graph shows a stable readability index of 7.5 to 8 until the 1930s, showing that in the late 19th century and the early 20th century congressional speeches were indexed at around the high middle school reading level. Since the 1930s, Starting the 1930s congressional speeches showed a constant increase in the readability index, peaking at around 10 in 1976, which is a ∼23% increase since 1939. In the late 1970s the trend reversed, and the readability index started to decrease gradually until an average index of below 9 in the beginning of the 21st century. One possible explanation to the simpler language of the speeches starting the 1970s can be related to the growing presence of the media that started during that time (
• Graber D.A.
• Dunaway J.
Mass Media and American Politics.
). With the media coverage of the congress activities, politicians could speak to an audience of legislators, but at the same time also communicate the speech to the general public through the media.
The graph also shows that Democratic speeches have a higher readability index compared to Republican speeches, and the difference has been becoming wider in the more recent years. Table 2 shows the mean readability index of Republican and Democratic speeches in several different decades. While Democratic speeches normally have a higher readability index than Republican speeches, in the 1930s that difference was reversed, and Republican speeches had higher readability index during that time.
Table 2Coleman-Liau readability index of Democratic and Republican speeches in different decades.
2000s8.95±0.0088.67±0.009<10−5
1980s9.58±0.0089.41±0.008<10−5
1930s8.04±0.0118.18±0.013<10−5
1870s7.66±0.0147.52±0.013<10−5
Although word diversity is not mathematically related to the Coleman-Liau readability index, the diversity of words in a speech can provide another measurement of the complexity of the speech. Fig. 5 shows that word diversity decreased gradually in the 19th century, and then increased during the 20th century until the 1970s. Starting the 1970s word diversity in speeches declined, and then increased again in the 21st century. The profile of change in word diversity is largely in agreement with the change in the readability index, although the two measurements are mathematically independent from each other.
As the figure shows, word diversity increased starting around the 1930s, peaked in 1969, and then gradually decreased until the beginning of the 21st century. That profile is very similar to the profile of change in the readability index, although the two measurements are independent. The graph also shows sudden increases of words diversity, mostly in Republican speeches in 1917, 1942, 1951, as well as a certain increase also in 1991. Interestingly, these are all years in which a war started. The year of 1874 was not used in the analysis due to a higher number of typos in the transcripts in these years, making 1874 different from other years in which the transcripts were accurate.
Table 3 shows the differences between word diversity in Republican speeches and Democratic speeches in different decades. The table shows that Republican speeches had a higher diversity of words until the 21st century, in which the word diversity in Democratic speeches became higher. The difference has also increased during the first decade of the 21st century, and in 2007 through 2010 the difference was 0.01 or higher, which is the highest difference since the beginning of the 20th century.
Table 3Diversity of words in Republican and Democratic congressional speeches.
YearDemocratsRepublicanst-test P
2000s0.472±0.00030.47±0.0004<0.0001
1990s0.47±0.00030.474±0.0003<0.0001
1980s0.482±0.00030.484±0.0003<0.0001
1970s0.484±0.00030.488±0.0004<0.0001
1960s0.482±0.00030.486±0.0004<0.0001
1950s0.469±0.00040.472±0.0005<0.0001
1940s0.463±0.00050.465±0.00070.02
1930s0.459±0.00050.461±0.00070.02
1920s0.461±0.00070.468±0.0006<0.0001
1910s0.456±0.00060.462±0.0005<0.0001
1900s0.431±0.00090.453±0.0007<0.0001
1890s0.443±0.00080.451±0.0007<0.0001
1880s0.450±0.00070.452±0.0007<0.04
1870s0.457±0.00090.466±0.0007<0.0001
Fig. 6 shows the change in word homogeneity. The graph shows that word homogeneity had been declining, which means that more recent congressional speeches tend to use the same set of words throughout the speech. Democratic speeches are more homogeneous than Republican speeches. The mean homogeneity of a Democratic speech is 0.0604$±4⋅10−5$, while Republican speeches have an average measured homogeneity of 0.0617$±4⋅10−5$. The two-tailed t-test statistical significance of the difference is $(P<10−5)$.
Congressional speeches have also changed in length. Fig. 7 shows the change in the mean number of words in a congressional speech in each year. The graph shows that congressional speeches were generally longer in the end of the 19th century, and became much shorter during the 20th century. Starting the 1980s, congressional speeches gradually became longer until the beginning of the 21st century, when the trend reversed and congressional speeches started to become shorter. For instance, in the 43rd through the 46th congress (1873-1876) an average congressional speech was ∼758±19 word long, while in 57th through the 61st congress (1901 through 1909) the average congressional speech was reduced to ∼652±5 words.
The graph also shows substantial differences between the length of Democratic and Republican speeches. For instance, in the decade of 1900-1909 the average length of a Democratic speech was 933±12.5 words, while the average Republican speech during the same time was 679±7.68 words long. In 2000 through 2009 the differences became much smaller, with slightly longer Republican speeches. During that time, the average Democratic speech was 703±2.7 words, while the average Republican speech was 718±3.5 words.
Another element that changed in congressional speeches over time is the sentiment expressed in the speeches. Fig. 9 shows the change in negative, very negative, positive, and very positive sentiments expressed in congressional speeches. The graph shows that both very positive and very negative sentiments became generally more common in the more recent years. The expression of stronger sentiments in congressional speeches forms a trend that changes in different years. Staring the 1980s, congressional speeches became less negative, and expressed more positive sentiments. The early 1960s were the years in which the positive sentiments expressed in speeches increased, peaking in 1964. The year of 1964 also shows substantial difference between the sentiments expressed in Democratic speeches and the sentiments expressed in Republican speeches. The peak in sentiments during that year and the differences between Democratic and Republican speeches could be related to the Civil Rights Act that was signed during that time.
The difference in sentiments expressed in speeches also changed between Republican and Democratic speeches. In the 2000s the average frequency of positive sentences in Democratic speeches was 0.1129±0.0003, while it was 0.1147±0.0004 in Republican speeches ($P<0.0001$). The frequency of negative sentences in the same decade showed higher average frequency of 0.284±0.0006 in Democratic speeches, compared to average frequency of 0.278±0.0007 in Republican speeches ($P<0.0001$).
The difference in sentiment could be related to the political affiliation of the president at the time. Table 4 and Fig. 8 show the frequency of negative sentiments from 2000 through 2010. Interestingly, the table shows that Democratic speeches expressed more negative sentiments in the years of 2000-2006, when the president was Republican, while in 2008-2010, when the president was Democrat, Republican speeches became more negative. In 2007 and 2008 no statistically significant difference in the negative sentences was identified.
Table 4Frequency of sentences expressing negative sentiments in Republican and Democratic speeches.
YearDemocratsRepublicanst-test P
20000.2422±0.00270.2366±0.00270.14
20010.302±0.0020.2886±0.0022<0.0001
20020.2887±0.00270.2812±0.00300.06
20030.3152±0.00190.3008±0.0021<0.0001
20040.2448±0.00290.2229±0.00310.0002
20050.2983±0.00210.2775±0.0022<0.0001
20060.2864±0.00260.2717±0.0027<0.0001
20070.3047±0.00170.3048±0.00190.97
20080.3183±0.00200.3204±0.00220.48
20090.2519±0.00200.2715±0.0022<0.0001
20100.2734±0.00280.2832±0.00340.02
However, the difference in negative sentiments does not change consistently with the political party of the president. For instance, in 1995 through 1999 Democratic speeches expressed more negative sentiments compared to Republican speeches despite a Democrat president during that time. Overall, no statistically significant difference in negative sentiments between Democratic and Republican speeches was identified between 1993 through 2000. During the Reagan administration, sentences that express negative sentiments were slightly more frequent in Democratic speeches (0.3466±0.0007) compared to Republican speeches (0.3448±0.0007), but with no statistical significance (P≃0.07). While Democratic speeches tend to include more negative sentences than Republican speeches between 1980 through 2010, Republican speeches were more negative during the 1930s and 1940s. In the 1930s, the frequency of negative sentences in Democratic speeches was 0.339±0.001, compared to 0.345±0.001 in speeches of Republican legislators.
## 5. Conclusions
The accessibility of digital archives and availability of computational tools enables data-driven analysis of text, providing a new approach to studying language and communication (
Cardie, C., Wilkerson, J., 2008. Text annotation for political science research.
;
• Grimmer J.
• Stewart B.M.
Text as data: the promise and pitfalls of automatic content analysis methods for political texts.
;
• Wilkerson J.
• Casas A.
Large-scale computerized text analysis in political science: opportunities and challenges.
). Here we used a large corpus of $∼106$ congressional speeches to analyze changes and trends in congressional speeches over time, as well as differences between speeches made by Republican and Democrat legislators. The large dataset of speeches covering a wide range of more than 100 years enables the analysis of the trends of changes in congressional speeches. Given the comprehensive analysis of a large number of text descriptors, this work can be used as a resource for further analysis of the long-term links between political speeches and other events or processes with political or societal nature.
The analysis shows a sharp increase in words related to women identity starting the 1980s. That change can be related to the change in the number of women in the congress, which has been increasing consistently since the 97th congress (1981). It can also be related to the higher number of bills related to topics relevant to women, which is naturally also a function of the number of women representatives.
An interesting trend was revealed by the Coleman-Liau readability index. The analysis shows a gradual increase in the readability index from a middle school level to high school level in the late 1970s, followed by a gradual and consistent decrease. The analysis also shows that speeches made by Democrat legislators have higher readability index compared to speeches of Republican legislators, and the difference has been becoming larger since the beginning of the 21st century. A very similar observation was made with the diversity of words, which is mathematically unrelated to the readability index but shows a very similar profile. The partisan split in the Coleman-Liau index correlates with the rise in partisanship beginning around 1995, as examined by
• Gentzkow M.
• Shapiro J.
Congressional record for the 43rd-114th congresses: parsed speeches and phrase counts.
, who identified textual framing of the Republican platform in 1994 with the increasing linguistic differences between parties.
The divergence in Coleman-Liau index suggests that such a modern partisan split may affect the style and form of their speeches as well as their content. The consistent decline in the readability index and diversity of words used in speeches can also be related to political speeches aiming at communicating with the general public through the media. The role of the media in increasing the power of the president was noticed by legislators at the time. For instance, in 1970 senator William Fulbright told congress that “Television has done as much to expand the powers of the president as would a constitutional amendment formally abolishing the co-equality of the three branches of the government” (
• Graber D.A.
• Dunaway J.
Mass Media and American Politics.
). The congress resisted radio and television broadcasting of most sessions until the 1970s (
• Graber D.A.
• Dunaway J.
Mass Media and American Politics.
). It is therefore possible that the increase in the broadcasting of speeches through the media and the presence of journalists in the congress gradually changed the purpose of speeches, as legislators started to address the media and the general public through their speeches.
Sentiment analysis shows that more recent speeches express stronger sentiments compared to speeches made in the 19th century, but negative sentiments expressed in speeches have been declining since the 1980s. Differences between parties show more negative sentiments in Republican speeches during the 71st through the 79th congress (1930s and 1940s). That changed in the following years, when Democratic speeches became somewhat more negative than Republican speeches. The analysis shows that since 2000, speeches of legislators from the opposite party of the president at the time the speech was made were more negative than speeches from legislators from the same political party as the president.
Due to the large size of the data, it is clear that the analysis done in this study is not possible without automation. The availability of computational tools for automatic text analysis enables new type of research of political communication, providing insights that are difficult to identify and quantify with traditional manual analysis. The method used in this study can be used for quantitative analysis of other large datasets of text data, enabling the detection of subtle trends and differences that are difficult to identify by manual analysis of the text.
## Declarations
### Author contribution statement
L. Shamir: Conceived and designed the experiments; Analyzed and interpreted the data; Contributed reagents, materials, analysis tools or data; Wrote the paper.
E. Tucker: Conceived and designed the experiments; Performed the experiments; Analyzed and interpreted the data; Wrote the paper.
C. Capps: Conceived and designed the experiments; Performed the experiments.
### Funding statement
This research did not receive any specific grant from funding agencies in the public, commercial, or not-for-profit sectors.
### Competing interest statement
The authors declare no conflict of interest.
No additional information is available for this paper.
## Acknowledgements
We would like to thank the two knowledgeable anonymous reviewers for the comments that helped to improve the manuscript.
## References
Pragmatic features of political speeches in english by some prominent nigerian leaders.
J. Polit. Discourse Anal. 2016; 2: 49-64
• Alluqmani A.
• Shamir L.
Writing styles in different scientific disciplines: a data science approach.
Scientometrics. 2018; 115: 1071-1085
• Bonikowski B.
• Gidron N.
The populist style in american politics: presidential campaign discourse, 1952–1996.
Soc. Forces. 2015; 94: 1593-1621
• Boromisza-Habashi D.
How are political concepts ‘essentially’ contested?.
Lang. Commun. 2010; 30: 276-284
1. Cardie, C., Wilkerson, J., 2008. Text annotation for political science research.
• Champion C.
Romans as BAPBAPOI: three polybian speeches and the politics of cultural indeterminacy.
Classical Philol. 2000; 95: 425-444
• Chung C.J.
• Park H.W.
Textual analysis of a political message: the inaugural addresses of two korean presidents.
Soc. Sci. Inf. 2010; 49: 215-239
• Coleman M.
• Liau T.L.
A computer readability formula designed for machine scoring.
J. Appl. Psychol. 1975; 60: 283
• Diermeier D.
• Godbout J.F.
• Yu B.
• Kaufmann S.
Language and ideology in congress.
Br. J. Polit. Sci. 2012; 42: 31-55
• Dowding K.
• Hindmoor A.
• Iles R.
• John P.
Policy agendas in australian politics: the governor-general's speeches, 1945–2008.
Aust. J. Polit. Sci. 2010; 45: 533-557
• Eshbaugh-Soha M.
The politics of presidential speeches.
in: Congress & the Presidency. Taylor & Francis, 2010: 1-21
• Fantham E.
The contexts and occasions of roman public rhetoric.
in: Roman Eloquence. Routledge, 2003: 102-116
• Gentzkow M.
• Shapiro J.
Congressional record for the 43rd-114th congresses: parsed speeches and phrase counts.
• Gentzkow M.
• Shapiro J.M.
Measuring group differences in high-dimensional choices: method and application to congressional speech.
Econometrica. 2019; 87: 1307-1340
• Graber D.A.
• Dunaway J.
Mass Media and American Politics.
CQ Press, 2017
• Grimmer J.
• Stewart B.M.
Text as data: the promise and pitfalls of automatic content analysis methods for political texts.
Polit. Anal. 2013; 21: 267-297
• Laver M.
• Benoit K.
• Garry J.
Extracting policy positions from political texts using words as data.
Am. Polit. Sci. Rev. 2003; 97: 311-331
• Mahdiyan M.
• Rahbar M.
• Hosseini-Maasoum S.M.
Applying critical discourse analysis in translation of political speeches and interviews.
Academic Journal of Interdisciplinary Studies. 2013; 2: 35
• Manning C.
• Surdeanu M.
• Bauer J.
• Finkel J.
• Bethard S.
• McClosky D.
The Stanford CoreNLP natural language processing toolkit.
in: Proceedings of 52nd Annual Meeting of the Association for Computational Linguistics. 2014: 55-60
• Pearson K.
• Dancey L.
Elevating women's voices in congress: speech participation in the house of representatives.
Polit. Res. Q. 2011; 64: 910-923
• Pepe C.
The Genres of Rhetorical Speeches in Greek and Roman Antiquity.
Brill, 2013
• Quinn K.M.
• Monroe B.L.
• Colaresi M.
• Crespin M.H.
An automated method of topic-coding legislative speech over time with application to the 105th-108th US senate.
in: Midwest Political Science Association Meeting. 2006: 1-61
• Quinn K.M.
• Monroe B.L.
• Colaresi M.
• Crespin M.H.
How to analyze political attention with minimal assumptions and costs.
Am. J. Polit. Sci. 2010; 54: 209-228
• Remer G.
Genres of political speech: oratory and conversation, today and in antiquity.
Lang. Commun. 2008; 28: 182-196
• Reyes A.
Building intimacy through linguistic choices, text structure and voices in political discourse.
Lang. Commun. 2015; 43: 58-71
• Savoy J.
Lexical analysis of us political speeches.
J. Quant. Linguist. 2010; 17: 123-141
• Schaffner C.
Political speeches and discourse analysis.
Curr. Issues Lang. Soc. 1996; 3: 201-204
• Scherer S.
• Layher G.
• Kane J.
• Neumann H.
• Campbell N.
An audiovisual political speech analysis incorporating eye-tracking and perception data.
in: Conference on Language Resource and Evaluation. 2012: 1114-1120
• Sensales G.
• Areni A.
• Giuliano L.
Pronouns and verbs as gender markers in italian parliamentary speeches: intersecting gender, communication, and politics.
Rass. Psicol. 2018; 34: 51-66
• Shamir L.
Compound quantitative analysis of text using machine learning.
Digital Scholarship in the Humanities. 2020; (fqaa007)
• Shamir L.
• Diamond D.
• Wallin J.
Leveraging pattern recognition consistency estimation for crowdsourcing data analysis.
IEEE Trans. Human-Mach. Syst. 2015; 46: 474-480
• Sim Y.
• Acree B.D.
• Gross J.H.
• Smith N.A.
Measuring ideological proportions in political speeches.
in: Proceedings of the 2013 Conference on Empirical Methods in Natural Language Processing. 2013: 91-101
• Socher R.
• Perelygin A.
• Wu J.
• Chuang J.
• Manning C.D.
• Ng A.
• Potts C.
Recursive deep models for semantic compositionality over a sentiment treebank.
in: Proceedings of the 2013 Conference on Empirical Methods in Natural Language Processing. 2013: 1631-1642
• Thomas M.
• Pang B.
• Lee L.
Get out the vote: determining support or opposition from congressional floor-debate transcripts.
in: Proceedings of the 2006 Conference on Empirical Methods in Natural Language Processing, Association for Computational Linguistics. 2006: 327-335
Politics, speech, and the art of persuasion: toward an aristotelian conception of the public sphere.
J. Polit. 1999; 61: 741-757
• Wilkerson J.
• Casas A.
Large-scale computerized text analysis in political science: opportunities and challenges.
Annu. Rev. Pol. Sci. 2017; 20: 529-544
• Yu B.
Language and gender in congressional speech.
Lit. Linguist. Comput. 2013; 29: 118-132
• Yu B.
• Kaufmann S.
• Diermeier D.
Classifying party affiliation from political speech.
J. Inf. Technol. Polit. 2008; 5: 33-48
|
{}
|
# American Institute of Mathematical Sciences
October 2015, 8(5): 881-888. doi: 10.3934/dcdss.2015.8.881
## On spiral solutions to generalized crystalline motion with a rotating tip motion
1 Shibaura Institute of Technology, Fukasaku 309, Minuma-ku, Saitama, 337-8570
Received January 2014 Revised March 2015 Published July 2015
In our previous paper we proposed a crystalline motion of spiral-shaped polygonal curves with a tip motion as a simple model of a step motion on a crystal surface under screw dislocation and discussed global existence of spiral solutions to the proposed model. In this paper we extend the previous results for generalized crystalline curvature flow with a suitable tip motion. We show that solution curves never intersect a trajectory of a tip and has no self-intersections. We also show that any facet never disappear during time evolution. Finally we show a time-global existence of the spiral-shaped solutions.
Citation: Tetsuya Ishiwata. On spiral solutions to generalized crystalline motion with a rotating tip motion. Discrete & Continuous Dynamical Systems - S, 2015, 8 (5) : 881-888. doi: 10.3934/dcdss.2015.8.881
##### References:
show all references
##### References:
[1] Tetsuya Ishiwata. On the motion of polygonal curves with asymptotic lines by crystalline curvature flow with bulk effect. Discrete & Continuous Dynamical Systems - S, 2011, 4 (4) : 865-873. doi: 10.3934/dcdss.2011.4.865 [2] Tetsuya Ishiwata. Crystalline motion of spiral-shaped polygonal curves with a tip motion. Discrete & Continuous Dynamical Systems - S, 2014, 7 (1) : 53-62. doi: 10.3934/dcdss.2014.7.53 [3] Tetsuya Ishiwata, Takeshi Ohtsuka. Numerical analysis of an ODE and a level set methods for evolving spirals by crystalline eikonal-curvature flow. Discrete & Continuous Dynamical Systems - S, 2021, 14 (3) : 893-907. doi: 10.3934/dcdss.2020390 [4] Tetsuya Ishiwata, Takeshi Ohtsuka. Evolution of a spiral-shaped polygonal curve by the crystalline curvature flow with a pinned tip. Discrete & Continuous Dynamical Systems - B, 2019, 24 (10) : 5261-5295. doi: 10.3934/dcdsb.2019058 [5] Tetsuya Ishiwata. Motion of polygonal curved fronts by crystalline motion: v-shaped solutions and eventual monotonicity. Conference Publications, 2011, 2011 (Special) : 717-726. doi: 10.3934/proc.2011.2011.717 [6] Matteo Novaga, Enrico Valdinoci. Closed curves of prescribed curvature and a pinning effect. Networks & Heterogeneous Media, 2011, 6 (1) : 77-88. doi: 10.3934/nhm.2011.6.77 [7] Petr Pauš, Shigetoshi Yazaki. Segmentation of color images using mean curvature flow and parametric curves. Discrete & Continuous Dynamical Systems - S, 2021, 14 (3) : 1123-1132. doi: 10.3934/dcdss.2020389 [8] Miroslav KolÁŘ, Michal BeneŠ, Daniel ŠevČoviČ. Area preserving geodesic curvature driven flow of closed curves on a surface. Discrete & Continuous Dynamical Systems - B, 2017, 22 (10) : 3671-3689. doi: 10.3934/dcdsb.2017148 [9] Doan The Hieu, Tran Le Nam. The classification of constant weighted curvature curves in the plane with a log-linear density. Communications on Pure & Applied Analysis, 2014, 13 (4) : 1641-1652. doi: 10.3934/cpaa.2014.13.1641 [10] Annalisa Cesaroni, Valerio Pagliari. Convergence of nonlocal geometric flows to anisotropic mean curvature motion. Discrete & Continuous Dynamical Systems, 2021, 41 (10) : 4987-5008. doi: 10.3934/dcds.2021065 [11] Shao-Yuan Huang. Exact multiplicity and bifurcation curves of positive solutions of a one-dimensional Minkowski-curvature problem and its application. Communications on Pure & Applied Analysis, 2018, 17 (3) : 1271-1294. doi: 10.3934/cpaa.2018061 [12] Y. Goto, K. Ishii, T. Ogawa. Method of the distance function to the Bence-Merriman-Osher algorithm for motion by mean curvature. Communications on Pure & Applied Analysis, 2005, 4 (2) : 311-339. doi: 10.3934/cpaa.2005.4.311 [13] Oleksandr Misiats, Nung Kwan Yip. Convergence of space-time discrete threshold dynamics to anisotropic motion by mean curvature. Discrete & Continuous Dynamical Systems, 2016, 36 (11) : 6379-6411. doi: 10.3934/dcds.2016076 [14] Yaiza Canzani, Dmitry Jakobson, Igor Wigman. Scalar curvature and $Q$-curvature of random metrics. Electronic Research Announcements, 2010, 17: 43-56. doi: 10.3934/era.2010.17.43 [15] Fabio Nicola. Remarks on dispersive estimates and curvature. Communications on Pure & Applied Analysis, 2007, 6 (1) : 203-212. doi: 10.3934/cpaa.2007.6.203 [16] Vittorio Martino. On the characteristic curvature operator. Communications on Pure & Applied Analysis, 2012, 11 (5) : 1911-1922. doi: 10.3934/cpaa.2012.11.1911 [17] Huyuan Chen, Dong Ye, Feng Zhou. On gaussian curvature equation in $\mathbb{R}^2$ with prescribed nonpositive curvature. Discrete & Continuous Dynamical Systems, 2020, 40 (6) : 3201-3214. doi: 10.3934/dcds.2020125 [18] Weimin Sheng, Caihong Yi. A class of anisotropic expanding curvature flows. Discrete & Continuous Dynamical Systems, 2020, 40 (4) : 2017-2035. doi: 10.3934/dcds.2020104 [19] Felipe Riquelme. Ruelle's inequality in negative curvature. Discrete & Continuous Dynamical Systems, 2018, 38 (6) : 2809-2825. doi: 10.3934/dcds.2018119 [20] Yves Coudène, Barbara Schapira. Counterexamples in non-positive curvature. Discrete & Continuous Dynamical Systems, 2011, 30 (4) : 1095-1106. doi: 10.3934/dcds.2011.30.1095
2020 Impact Factor: 2.425
|
{}
|
## Linear and Convex Tori
Here’s a picture of what’s basically a neighborhood of a constant radius torus in the cylindrical model of a contact structure — mod out by the z-action, of course. Okay, so I’ve reembedded this… (you could look at the xz-plane modded out by a lattice too).
The intersection of the contact planes with a surface in a contact manifold gives a (typically singular) line field on the surface. This line field integrates to give the characteristic foliation.
In this model, intersecting the contact planes with the surface suggests the line field and hence the characteristic foliation. In the present case, this is quite literal.
The reembedding was chosen so that the characteristic foliation is a bunch of vertical parallel circles. Nearby constant radius tori will also have characteristic foliations by circles or lines according to the rationality of the slope of the line field. I tend to call thusly situated tori linear.
Linear tori have their place in the theory of contact structures, but this linear ability is special to surfaces of euler characteristic 0. The notion of convexity however applies to all surfaces.
A surface in a contact manifold is convex if in some neighborhood of the surface there is a transverse flow that preserves the contact structure. Think about translating the xy-plane of the standard euclidean model in the z direction — or think about a constant radius neighborhood of the x-axis in this model. The motivating thing is that every surface is $C^\infty$ close to a convex surface. (That’s not quite the whole story for a surface with boundary.)
So let us perturb our linear torus into a convex torus. We may do so by picking two circles in the characteristic foliation of the linear torus and pushing the interiors of the complementary annuli to opposite sides of the torus.
Intersecting with the contact planes suggests the characteristic foliation.
This characteristic foliation has only two closed circle leaves and the rest are lines. The contact preserving transverse flow is a bit harder to see here… it’s not just expansion in the radial direction. For instance, along the two closed leaves it will have to be tangent to the former linear torus. (We’ll save this for another time.)
There are many ways of perturbing a surface into a convex one…
|
{}
|
zbMATH — the first resource for mathematics
Existence of symmetric homoclinic orbits for systems of Euler-Lagrange equations. (English) Zbl 0589.34029
Nonlinear functional analysis and its applications, Proc. Summer Res. Inst., Berkeley/Calif. 1983, Proc. Symp. Pure Math. 45/2, 447-459 (1986).
[For the entire collection see Zbl 0583.00018.]
This paper gives the original version of some theorems in $${\mathbb{R}}^ 2$$ which were subsequently generalised. The basic observation is that certain dynamical systems with indefinite Hamiltonian structure have orbits which are monotone in position space (not configuration or phase space), and that as a consequence the existence of homoclinic orbits can be inferred for the general theory [see H. Hofer and the author, Math. Ann. 268, 387-403 (1984; Zbl 0569.70017)].
MSC:
34C15 Nonlinear oscillations and coupled oscillators for ordinary differential equations 37-XX Dynamical systems and ergodic theory 34A34 Nonlinear ordinary differential equations and systems, general theory 34C28 Complex behavior and chaotic systems of ordinary differential equations
|
{}
|
# Homework Help: Torque/Rigid body rotation
1. Aug 30, 2012
### decerto
1. The problem statement, all variables and given/known data
This is problem 7.7 from [kleppners mechanics book]http://books.google.ie/books?id=Hmq...rough a point on the rim of the hoop"&f=false but its also a general question on understanding this type of problem.
2. Relevant equations
L=Iω
dL/dt=ΩL=rxF
3. The attempt at a solution
The standard approach appears to be compute the angular momentum from Iω and find how it changes with respect to time, generally its ΩL where Ω is the precession about the axis, then compute the relevant torque and set them equal and solve for whatever your looking for.
My problems arises in 7.7 as the force creating the torque(the tension in the string) is at an angle to axis and the r from r x F is also at angle to the axis. So I'm not quite sure how I get the relevant force, I'm thinking it's as simple as r x (perp component of T) but I'm not 100%.
I'm also not sure since, I'm breaking down ω as a vector into components, perp and parallel to the hoop, then computing the spin angular momentum from the perp ω and ignoring the parallel ω one. But I'm not sure if you can just do that in this problem because the way the torque is setup, maybe I need to include the other component of angular momentum into it?.
Help would be much appreciated.
As they say solve it approximately with small angles, I assume that means cosx=1 and sinx=x
Right now for dL/dt i.e ΩL I have MR^2 ω^2 β
and for the torque I have with T=Mg torque=RMg(1+αβ)
2. Aug 31, 2012
### voko
Google does not want to show that part of book anymore. You will have to reproduce the problem here to get any help.
3. Aug 31, 2012
### decerto
Really? It shows me it just fine when I click on the link
http://www.maths.tcd.ie/~kovacs/Teaching/Mechanics/Kleppner-Kolenkow.pdf [Broken]
page 352 question 7.7
Last edited by a moderator: May 6, 2017
4. Sep 1, 2012
### voko
I have looked through the whole chapter in the book, and I have a question: how is the hoop different from a gyroscope tilted down?
|
{}
|
# fihyph – Hyphenation patterns for Finnish language
Two sets of hyphenation patterns are provided; fihyph.tex, and fi8hyph.tex (which is modified from fihyph.tex to make the Finnish accented letters to work with , adding some \catcode, \uccode, and \lccode commands after the model used in the hyphenation files for the other European languages).
The package is superseded by the Finnish patterns available in the hyph-utf8 bundle.
Sources `/language/hyphenation/fihyph` Licenses Public Domain Software Maintainer Timo Hellgren Contained in TeX Live as hyphen-finnish Topics HyphenationFinnish
## Suggestions
Maybe you are interested in the following packages as well.
more
|
{}
|
# How do you find (dy)/(dx) given y^4=100x?
Apr 16, 2017
#### Explanation:
Implicitly differentiate: ${y}^{4} = 100 x$:
$4 {y}^{3} \frac{\mathrm{dy}}{\mathrm{dx}} = 100$
Divide both sides by $4 {y}^{3}$:
$\frac{\mathrm{dy}}{\mathrm{dx}} = 25 {y}^{-} 3$
If you do not want to leave it like this, then you would have been better off solving for y and then differentiating as follows:
$y = \sqrt{10} {x}^{\frac{1}{4}}$
$\frac{\mathrm{dy}}{\mathrm{dx}} = \frac{\sqrt{10}}{4} {x}^{- \frac{3}{4}}$
|
{}
|
How To Clear The Entire Sheet Or Specified Range In Excel?
MS Word Online Training
32 Lectures 2.5 hours
MS Excel Online Training
Best Seller
102 Lectures 10 hours
Advanced Excel (Power Query) Online Training
56 Lectures 5.5 hours
Do you often encounter too much data and spend a lot of time selecting and clearing Excel sheets?
If so, this tutorial will be helpful to you.
When analysing elaborative Excel worksheets, removing non-relevant information often makes it easier to study them. This tutorial explains how to clear an entire spreadsheet and a specified range in MS Excel using two simple methods
Method 1: How to Clear The Entire Sheet?
This is an easy procedure. If you want to clear the entire sheet, you can use a keyboard shortcut or from the corner cell. We learn how to do it in a few steps.
Step 1 − Select the top left corner cell between the rows and the column headers.
Step 2 − Right-click and choose "Delete" from the drop-down menu.
Following this, the spreadsheet would be clean of all data.
You can also use an alternative approach. Using the keyboard shortcut, press Control + A to select all cells in the spreadsheet. Then right-click and repeat step 2, and the result will be the same as above.
Method 2: How To Clear a Specified Range?
Suppose you want to clear only a particular set of cells in the spreadsheet. Doing so one by one could be cumbersome. However, using the Visual Basic for Applications (VBA), you can remove one or more specified ranges of cells from your spreadsheet.
The VBA is a computer programming language developed by Microsoft. It automates repetitive and routine tasks, simplifying the process of working out complex data sets. Let's understand how this works using the same data set mentioned earlier.
Step 1 − Press the Alt + F11 keys to open the Microsoft Excel Visual Basic Editor dialogue box.
Step 2 − Right-click on "Microsoft Excel Objects", and from the drop-down menu, select Insert → Module.
Step 3 − Paste the mentioned VBA code in the top right box after inserting the module to clear only a specified range of cells. Let's say we want to remove only the table with the range C8 to F12 highlighted in green. We modify the range in the code.
VBA Code to clear specific range of cells from Excel sheet −
Sub sbClearCells()
Range("C8:F12").Clear
End Sub
Step 4 − Press F5 on your keyboard or click the "Run Program" button to execute the code.
The resulting table will look like this.
Step 5 − If you want to remove multiple ranges of cells from your spreadsheet, you can modify the VBA code mentioned above and do it in one easy step.
Suppose you want to remove cells A3 to B5; cells D13 to F15; and cells B10 to C11. Enter the code in the Module window and repeat step 3.
Sub sbClearCells()
Range("A3:B5").Clear
Range("D13:F15").Clear
Range("B10:C11").Clear
End Sub
The VBA program will clear the selected ranges from the spreadsheet.
Conclusion
This tutorial demonstrated how to clear a specific cell range in Excel and an entire sheet. You can quickly and efficiently perform customised tasks with VBA code as well. With Excel tutorials, you can master and use the program in your work and everyday life.
Updated on 20-Sep-2022 07:37:40
|
{}
|
## LaTeX forum ⇒ BibTeX, biblatex and biber ⇒ Lines
Information and discussion about BiBTeX - the bibliography tool for LaTeX documents.
Georg
Posts: 58
Joined: Mon Jan 29, 2018 4:25 pm
### Lines
Hello folks,
I have a question below:
Any help? Thanks
Attachments
lines.jpg (36.59 KiB) Viewed 374 times
Stefan Kottwitz
Posts: 8905
Joined: Mon Mar 10, 2008 9:44 pm
Hi Georg,
that's easy, such as
`\usepackage[hidelinks]{hyperref}`
or:
`\hypersetup{hidelinks}`
Stefan
Georg
Posts: 58
Joined: Mon Jan 29, 2018 4:25 pm
Hi Stefan,
I want links (frame) only around authors but not around the page number. We can see that it covers the page number also because the half of the link is in the next page.
Stefan Kottwitz
Posts: 8905
Joined: Mon Mar 10, 2008 9:44 pm
This removes the link border color (sets it to white) and sets the color for cite borders:
`\usepackage{hyperref}\hypersetup{ colorlinks = false, linkbordercolor = {white}, citebordercolor = {0 1 0},}`
Stefan
Georg
Posts: 58
Joined: Mon Jan 29, 2018 4:25 pm
Hallo, Sterfan
Thank you but your suggestion does not work.
Stefan Kottwitz
Posts: 8905
Joined: Mon Mar 10, 2008 9:44 pm
Hi Georg,
it works for me, I tested the code.
Perhaps post your code (reduced, minimal, but compilable) that shows error or non-function. So we can see why it doesn't.
Stefan
Georg
Posts: 58
Joined: Mon Jan 29, 2018 4:25 pm
Hi Stefan,
The code is so long and I dont know which part to reduce. What is the name for this problem?
Thanks a lot
Georg
Posts: 58
Joined: Mon Jan 29, 2018 4:25 pm
Hi dear members,
do you have any ideas how to solve this problem?
Thanks a lot
Stefan Kottwitz
Posts: 8905
Joined: Mon Mar 10, 2008 9:44 pm
Have a look at this explanation: How to make a “minimum example”.
You can build up a document that shows the error behavior (your preamble and some dummy text) or hack down a copy of your document.
Once you post a copy here, it can be tested and fixed.
Stefan
Georg
Posts: 58
Joined: Mon Jan 29, 2018 4:25 pm
Dear Stefan,
Thank you for your timely responses. It is really great.
Can you please provide some ideas why this problem occurs and what should we approximately do?
Thanks a lot
|
{}
|
## Wednesday, April 3, 2013
### limitations of the NFW-profile shape
the NFW-profile is an approximation to the density distribution inside cold dark matter structures. where does the NFW-approximation break down and for what reason? if there was annihilation of dark matter, what could you say about the central brightness?
bonus question: where is the first minimum of $x^{\sin(x)}$, $x>0$?
1. the NFW-profile shape needs to break down at small radii because the density diverges $\propto 1/r$ and it needs to be truncated at large radii because the total mass diverges logarithmically. if there was CDM annihilation with a luminosity density $\propto\rho^2$ you'd get infinite integrated luminosity if the profile were just a bit steeper than $1/r$ in the centre.
2. This is cool!
3. The bonus question:
Set:
$$f(x)=x^{\sin(x)}$$
$$=> f'(x)=\frac{sin(x)*cos(x)}{x}*f(x)$$
as:
$$f(x)> 0 for$$ $$x > 0$$
$$f'(x)= 0 => \frac{sin(x)*cos(x)}{x}=0$$
$$=> sin(x)*cos(x)=0$$
so there first minimum is at $$x = \frac{\pi}{4}$$
|
{}
|
# Homework Help: Does limit exist as x approaches zero? Frobenius Method DEQ
1. Apr 13, 2013
### lonewolf219
1. The problem statement, all variables and given/known data
what is the limit of (4x^2-1)/(4x^2)
when x→0
2. Relevant equations
In order to find the Indicial Equation, do I need to take the limit of p(x) and q(x), the non-constant coefficients? If so, can the limit of this function be found using LH Rule?
3. The attempt at a solution
Please let me know any info you might have about the Frobenius Method, since I am just learning it from my professor's brief notes about it...
2. Apr 13, 2013
### LCKurtz
What do you think? What have you tried?
3. Apr 13, 2013
### lonewolf219
Well, can you use L' Hopital's Rule twice? (8x - 0)/(8x) and then (8/8) = 1 ?
But I'm confused if I need to multiple by x^2 to find q(nault)?
x^2*q(x)=q(nault)
y''(x) + p(x)y'(x) + q(x)y(x) = 0
If so, would the limit be -1/4?
x^2(4x^2-1)/(4x^2) = [(4x^4)/4x^2] - [x^2/(4x^2)] = [x^2] - [1/4] = [x=0] = - 1/4
Last edited: Apr 13, 2013
4. Apr 13, 2013
### HallsofIvy
L'Hopital applies only when the numerator and denominator both go to 0. Here, if x= 0, the numerator is -1 but the denominator is 0. Suppose x were some very small number, say x= 0.000001. What would that fraction be? Now, what do you thing the limit is?
5. Apr 13, 2013
### lonewolf219
negative infinity, right?
|
{}
|
Using a set of matrices exhibits all the algebraic structure of complex numbers including a matrix with real entries that corresponds to $\sqrt -1$. Having established the model it is more convenient to use the $x+i y$ notation rather than use the matrices.
Using a set of linear combinations of matrices exhibits all the algebraic structure of quaternions including three different matrices corresponding to the three different square roots of -1. Again, having established the model, it is more convenient to use the $a + {\bf i}x + {\bf j}y + {\bf k}z$ notation rather than to use the matrices.
|
{}
|
# find a matrix $A_{n \times n}$ which satisfy $A^{n}=0$ and $A^{n-1}\ne0$
I asking a question for my brother. He just started his algebra course not long ago and he got a question he is stuck on (he just started the course so all his knoweldge is based on matrices and their properties).
I need to find a Matrix $$A_{2x2} \not=0$$ which satisfies $$A^2=0$$.
Also, I need to find a Matrix $$A_{3x3}$$ which satisfies $$A^3=0$$ and $$A^2\not=0$$.
In the end I need to generalize the problem to $$A_{n \times n}$$ (find a matrix $$A_{n \times n}$$ which satisfy $$A^{n}=0$$ and $$A^{n-1}\ne0$$).
In the first question I wrote $$A$$ as
$$\begin{bmatrix} a & b \\ c & d \end{bmatrix}$$
after multiplying $$A$$ with itself I found out that every matrix $$2x2$$ in the form of
$$\begin{bmatrix} x & y \\ -\frac{x^2}{y} & -x \end{bmatrix}$$
when multiplied with itself equal zero.
In the second question I tried the same thing but it got to long to soon so I figured I am doing something wrong. also, the the equations I get when I am trying to find conditions for $$A$$ are to messy to deal with (9 in total).
I did manage to find some matrices that satisfies $$A^3=0$$ such as
$$\begin{bmatrix} 0 & 1 & 1 \\ 0 & 0 & 1 \\ 0 & 0 & 0 \end{bmatrix}$$
but I still wish to know how should I find the conditions for it to happen.
About the third question, I guess I need to finish the second one to even begin thinking about the solution but I still can't see where should I start.
Try this: $$A = \begin{bmatrix} \color{red}0 & 1 & 1 & ... & 1 \\ 0 & \color{red}0 & 1 & ... & 1 \\ ... & ... & ... & ... & ...\\ 0 & 0 & 0 & ... & 1 \\ 0 & 0 & 0 & ... & \color{red}0 \end{bmatrix}$$
Just to feel what will happen: $$A^2 = \begin{bmatrix} 0 & 1 & 1 & ... & 1 \\ 0 & 0 & 1 & ... & 1 \\ ... & ... & ... & ... & ...\\ 0 & 0 & 0 & ... & 1 \\ 0 & 0 & 0 & ... & 0 \end{bmatrix}\begin{bmatrix} 0 & 1 & 1 & ... & 1 \\ 0 & 0 & 1 & ... & 1 \\ ... & ... & ... & ... & ...\\ 0 & 0 & 0 & ... & 1 \\ 0 & 0 & 0 & ... & 0 \end{bmatrix}$$$$= \begin{bmatrix} \color{red}0 & \color{blue}0 & 1 & 2& ... & n-1 \\ 0 & \color{red}0 & \color{blue}0 & 1& ... & n-2 \\ ... & ... & ...&... & ... & ...\\ 0 & 0 & 0 & 0& ... & \color{blue}0 \\ 0 & 0 & 0 & 0&... & \color{red}0 \end{bmatrix}$$ Each time you raise to another power, the upper diagonals will start to vanish consequently (actually, you can find an explicit formula for the $$n^\text{th}$$ power quite easily). Then, notice that $$A^{n-1} \ne O$$ but $$A^n = O$$.
If you think about the first part in linear transformation terms, you want a map $$A: \Bbb{R}^2 \to \Bbb{R}^2$$ for which $$A(A \vec{v}) = \vec{0}$$ for any vector $$\vec{v}$$.
One option for such a transformation would be $$\langle x, y \rangle \mapsto \langle 0, x \rangle.$$ What would be the matrix of this transformation?
• Thank you for the help. As I have mentioned before I just started the course so all my knoweldge is based on matrices and their properties. Dec 5 '20 at 19:41
|
{}
|
Chapter 6. The solution of thermodynamic problems The Second Law Entropy Apppp pylications of Entropy this is not the case There are numerous examples ofthis Entropy is related to heat and heat flow and
22. [Entropy Example Problems I] Physical Educator
THERMODYNAMICS OF SOLUTIONS UPM. The Second Law Entropy Apppp pylications of Entropy this is not the case There are numerous examples ofthis Entropy is related to heat and heat flow and, Solving thermodynamic problems can be made significantly easier by following a rigorous process. One such process is outlined below. Summarize given data in own words.
Improve your skills with free problems in 'Solving problems involving the change in entropy of a system using the Recognizing examples of the second law of Give an example of a process in which no the 2nd Law of Thermodynamics? Sample Problems more than compensates for the entropy decrease in your room. Problems
enthalpy problems and answers.pdf FREE Enthalpy Change of Water Chemistry Example Problem below are a collection of problems lifted from the entropy chapter Chapter 19: Thermochemistry II: Entropy and free Energy OWL Example Problem The entropy of a system measures the number of ways the system can be
Try these problems for yourself before checking the detailed answers! Ex. 1 Two identical blocks of iron, one at 100 C and the other at 0 C, are brought into thermal Thermodynamics of solutions 2 suspensions, treated under the heading . Reacting mixtures are covered in Mixture settling Chemical reactions, aside.
• solve problems involving compressible flow There are other cases where the entropy is constant. For example, Entropy is used in the solution of gas and Entropy and the Second Law of Thermodynamics . provides an example of the difference between the entropy of a to see a solution to Practice Problem 4.
B. Examples 1. Simple fluids 2. Integral solutions 2. Entropy solutions 3. Condition E 4. Kinetic formulation 5. An exit problem a. • Spontaneous solution processes are Chemical Thermodynamics Example 9.2 Chemical Thermodynamics Entropy on the Molecular Scale
noisy optimization problems. 1 Introduction The cross-entropy for example, (Rubinstein and Kroese 2007; Cross-Entropy Method for Optimization The second law leads to the definition of a new property called entropy. The Clausius Inequality The first For example entropy change of Solution The network
Homework 1 Solution 1. reducing entropy. The trick, then, for this problem, Give examples of X, Y and Z for the following inequalities 5. Ductless problem Solution properties and under Cold pads. Entropy is the final answer. Entropy cannot be destroyed (consumed),
Thermodynamics of solutions 2 suspensions, treated under the heading . Reacting mixtures are covered in Mixture settling Chemical reactions, aside. The statistical thermodynamics definition of entropy: $S = kN \ln (W)$ troubles me a lot with the problem of dimenstions. where $S$ is entropy; $k$, the Boltzmann
The Second Law Entropy Apppp pylications of Entropy this is not the case There are numerous examples ofthis Entropy is related to heat and heat flow and • solve problems involving compressible flow There are other cases where the entropy is constant. For example, Entropy is used in the solution of gas and
Chapter 6: Entropy and the Laws of Thermodynamics Goals of Period 6 (Example 6.1) What is the change in entropy when 100 grams of ice at 0 oC melt into 100 enthalpy problems and answers.pdf FREE Enthalpy Change of Water Chemistry Example Problem below are a collection of problems lifted from the entropy chapter
Chapter 6. The solution of thermodynamic problems. Journal of Probability and Statistics is a peer Let us denote by the solution to problem “Maximum entropy in the problem of moments,” Journal of, Entropy Change Example Problem Solution. Entropy of a reaction refers to the positional probabilities for each reactant. An atom in gas phase has more options.
Example 7B 3 Entropy Change of an Isobaric Process
Problems with units of entropy in statistical. Example Problem with Complete Solution . Entropy Change of an Isobaric Process None of the assumptions made in this problem solution can be verified. Answers :, 5.06a Gibbs Free Energy Example Problem 1. To view this video please enable JavaScript, Entropy and Free Energy are defined and utilized for this purpose..
enthalpy problems and answers Bing - shutupbill.com. That departure is the main reason for interest in entropy of mixing. These energy and entropy For example, two entropy of mixing for polymer solutions,, Solutions to sample quiz problems and assigned Quiz Problem 6. Give three examples of systems where the ergodic Solution. The Gibbs formula for the entropy is.
Quiz Energy and Entropy CliffsNotes Study Guides
224 May 20 1999 Elements of Fluid Mechanics and. Answers to Chemistry Problems Online Quizzes for CliffsNotes Chemistry QuickReview, 2nd Edition; Quiz: Energy and Entropy Discovery and Similarity 6/06/2012В В· The problem statement, Homework Help: Thermodynamics question, entropy Example May 7, 2011 #1. The attempt at a solution.
Problem Solutions. Fund. of Renewable of energy and a certain amount of entropy. While the latter is well defined, Solution of Problem 9.1 0100131. Thermodynamics of solutions 2 suspensions, treated under the heading . Reacting mixtures are covered in Mixture settling Chemical reactions, aside.
6/06/2012В В· The problem statement, Homework Help: Thermodynamics question, entropy Example May 7, 2011 #1. The attempt at a solution 5.06a Gibbs Free Energy Example Problem 1 5:12. 5.06b Gibbs Free Energy Example Problem 2 then you would have an increase in entropy. Now in their previous
B. Examples 1. Simple fluids 2. Integral solutions 2. Entropy solutions 3. Condition E 4. Kinetic formulation 5. An exit problem a. Physics problems: thermodynamics. Solution . Problem 3. How many btu are needed to change 10 pounds of ice at 5 degree Fahrenheit to steam at 250 degree Fahrenheit?
Problem 1. [20 Points] Liquid ethanol at 25 C, 1 atm enters a combustion chamber operating at steady state and burns with air which is entering the chamber at 227 C LECTURES ON PROBABILITY, ENTROPY, AND STATISTICAL PHYSICS 2.11 Examples from data analysis urgent problem demanding an immediate solution
A comprehensive treatment of Entropy, free energy and the Second Law of Thermodynamics for students of The problem example below works this out in detail The statistical thermodynamics definition of entropy: $S = kN \ln (W)$ troubles me a lot with the problem of dimenstions. where $S$ is entropy; $k$, the Boltzmann
B. Examples 1. Simple fluids 2. Integral solutions 2. Entropy solutions 3. Condition E 4. Kinetic formulation 5. An exit problem a. The Second Law Entropy Apppp pylications of Entropy this is not the case There are numerous examples ofthis Entropy is related to heat and heat flow and
4.3 Methodology for Solving Thermodynamics Problems 159 EXAMPLE of Thermodynamics 249 EXAMPLE 6.4-1: ENTROPY Entropy Generation 257 6.5.2 Solution Lectures on Heat and Thermodynamics Entropy in Irreversible Change: The problem with these subjective perceptions of heat is that they may not be the same for
Chemical Thermodynamics. Example Problem: Enthalpy solution. Entropy Practice Problem: Given the following entropy values Al 2 O 3 (s) Improve your skills with free problems in 'Solving problems involving the change in entropy of a system using the Recognizing examples of the second law of
Practice Problem 4. Calculate the standard-state entropy of reaction for the following reactions and explain Solution (a) Using a standard-state entropy data Watch the video solution for the question: In which example does entropy increase? I. A...
The statistical thermodynamics definition of entropy: $S = kN \ln (W)$ troubles me a lot with the problem of dimenstions. where $S$ is entropy; $k$, the Boltzmann Thermodynamics part 3: Kelvin scale and Ideal gas law example (Opens a modal) Reconciling thermodynamic and state definitions of entropy (Opens a modal)
Download Entropy Problems And Solutions Pdf chapter 20 entropy and the second law of thermodynamics example with the ice and water Chapter 19: Thermochemistry II: Entropy and free Energy OWL Example Problem The entropy of a system measures the number of ways the system can be
To accomplish this in JavaScript, try element.parentNode. Access a Parent Element With JavaScript or jQuery. Here’s a JavaScript example. Javascript get element by class example Blackfalds Document.getElementById() method in javascript with example, What are the usage of document.getElementById() method? Explanation of getElementById() method is given
Entropy of mixing Wikipedia
Thermodynamics of refrigeration UPM. The statistical thermodynamics definition of entropy: $S = kN \ln (W)$ troubles me a lot with the problem of dimenstions. where $S$ is entropy; $k$, the Boltzmann, The second law leads to the definition of a new property called entropy. The Clausius Inequality The first For example entropy change of Solution The network.
Entropy and Information Gain Computer Science
enthalpy problems and answers Bing - shutupbill.com. Try these problems for yourself before checking the detailed answers! Ex. 1 Two identical blocks of iron, one at 100 C and the other at 0 C, are brought into thermal, Entropy Example Problems. It then provides example problems to allow the user to Try to solve the two example problems before watching the solutions in the.
• solve problems involving compressible flow There are other cases where the entropy is constant. For example, Entropy is used in the solution of gas and Solving thermodynamic problems can be made significantly easier by following a rigorous process. One such process is outlined below. Summarize given data in own words
Thermodynamics: Examples for chapter 3. 1. By using the relation given in the problem, of the entropy changes in the reversible adiabatic expansion and the Try these problems for yourself before checking the detailed answers! Ex. 1 Two identical blocks of iron, one at 100 C and the other at 0 C, are brought into thermal
Download Entropy Problems And Solutions Pdf chapter 20 entropy and the second law of thermodynamics example with the ice and water Ductless problem Solution properties and under Cold pads. Entropy is the final answer. Entropy cannot be destroyed (consumed),
Entropy and the Second Law of Thermodynamics . provides an example of the difference between the entropy of a to see a solution to Practice Problem 4. 4.3 Methodology for Solving Thermodynamics Problems 159 EXAMPLE of Thermodynamics 249 EXAMPLE 6.4-1: ENTROPY Entropy Generation 257 6.5.2 Solution
Thermodynamics part 3: Kelvin scale and Ideal gas law example (Opens a modal) Reconciling thermodynamic and state definitions of entropy (Opens a modal) LECTURES ON PROBABILITY, ENTROPY, AND STATISTICAL PHYSICS 2.11 Examples from data analysis urgent problem demanding an immediate solution
Spontaneous Processes and Entropy Examples of a spontaneous and nonspontaneous process. A Problem To Consider Evaporator 7 S psia lb,.min uc./uc system as a wt101e and then compare the values. Heat transfer within the condenser and evaporator occurs at temperatures of
1 Entropy change in the isobaric-isochoric cycle of an ideal gas Solution : In the isobatic Using the results of the solution of the previous problem, B. Examples 1. Simple fluids 2. Integral solutions 2. Entropy solutions 3. Condition E 4. Kinetic formulation 5. An exit problem a.
5.06a Gibbs Free Energy Example Problem 1 5:12. 5.06b Gibbs Free Energy Example Problem 2 then you would have an increase in entropy. Now in their previous Chapter 19: Thermochemistry II: Entropy and free Energy OWL Example Problem The entropy of a system measures the number of ways the system can be
Entropy changes in the hot brick problem'' The reversible process has zero total change in entropy. Muddy Points. On the example of free expansion versus Practice Problem 4. Calculate the standard-state entropy of reaction for the following reactions and explain Solution (a) Using a standard-state entropy data
5.06a Gibbs Free Energy Example Problem 1. To view this video please enable JavaScript, Entropy and Free Energy are defined and utilized for this purpose. 4.3 Methodology for Solving Thermodynamics Problems 159 EXAMPLE of Thermodynamics 249 EXAMPLE 6.4-1: ENTROPY Entropy Generation 257 6.5.2 Solution
Entropy and Information Gain. This is mostly based PowerPoint slides written by Andrew W. Moore of Carnegie Mellon University. Birdie seed example. Practice Problem 4. Calculate the standard-state entropy of reaction for the following reactions and explain Solution (a) Using a standard-state entropy data
Entropy and Information Gain Computer Science
Free Entropy Problems And Solutions PDF nodejsdublin.com. The second law leads to the definition of a new property called entropy. The Clausius Inequality The first For example entropy change of Solution The network, • solve problems involving compressible flow There are other cases where the entropy is constant. For example, Entropy is used in the solution of gas and.
Practice Problem 4 chemed.chem.purdue.edu
Solving Thermodynamics Problems University of Minnesota. Try these problems for yourself before checking the detailed answers! Ex. 1 Two identical blocks of iron, one at 100 C and the other at 0 C, are brought into thermal 4.3 Methodology for Solving Thermodynamics Problems 159 EXAMPLE of Thermodynamics 249 EXAMPLE 6.4-1: ENTROPY Entropy Generation 257 6.5.2 Solution.
Spontaneous Processes and Entropy Examples of a spontaneous and nonspontaneous process. A Problem To Consider The second law leads to the definition of a new property called entropy. The Clausius Inequality The first For example entropy change of Solution The network
Spontaneous Processes and Entropy Examples of a spontaneous and nonspontaneous process. A Problem To Consider 5.06a Gibbs Free Energy Example Problem 1 5:12. 5.06b Gibbs Free Energy Example Problem 2 then you would have an increase in entropy. Now in their previous
Physics problems: thermodynamics. Solution . Problem 3. How many btu are needed to change 10 pounds of ice at 5 degree Fahrenheit to steam at 250 degree Fahrenheit? Chemical Thermodynamics. Example Problem: Enthalpy solution. Entropy Practice Problem: Given the following entropy values Al 2 O 3 (s)
Problem Set 12 Solutions 1. What is the increase in entropy of one gram of ice at OoC is melted and heated to 500C? The change in entropy is given by dS = dQ 4.3 Methodology for Solving Thermodynamics Problems 159 EXAMPLE of Thermodynamics 249 EXAMPLE 6.4-1: ENTROPY Entropy Generation 257 6.5.2 Solution
Ductless problem Solution properties and under Cold pads. Entropy is the final answer. Entropy cannot be destroyed (consumed), Thermodynamics: Examples for chapter 3. 1. By using the relation given in the problem, of the entropy changes in the reversible adiabatic expansion and the
Entropy Example Problems. It then provides example problems to allow the user to Try to solve the two example problems before watching the solutions in the LECTURES ON PROBABILITY, ENTROPY, AND STATISTICAL PHYSICS 2.11 Examples from data analysis urgent problem demanding an immediate solution
6/06/2012В В· The problem statement, Homework Help: Thermodynamics question, entropy Example May 7, 2011 #1. The attempt at a solution noisy optimization problems. 1 Introduction The cross-entropy for example, (Rubinstein and Kroese 2007; Cross-Entropy Method for Optimization
Homework 1 Solution 1. reducing entropy. The trick, then, for this problem, Give examples of X, Y and Z for the following inequalities 5. 1 Entropy change in the isobaric-isochoric cycle of an ideal gas Solution : In the isobatic Using the results of the solution of the previous problem,
• Spontaneous solution processes are Chemical Thermodynamics Example 9.2 Chemical Thermodynamics Entropy on the Molecular Scale Chapter 6: Entropy and the Laws of Thermodynamics Goals of Period 6 (Example 6.1) What is the change in entropy when 100 grams of ice at 0 oC melt into 100
5.06a Gibbs Free Energy Example Problem 1. To view this video please enable JavaScript, Entropy and Free Energy are defined and utilized for this purpose. Problem Set 12 Solutions 1. What is the increase in entropy of one gram of ice at OoC is melted and heated to 500C? The change in entropy is given by dS = dQ
Try these problems for yourself before checking the detailed answers! Ex. 1 Two identical blocks of iron, one at 100 C and the other at 0 C, are brought into thermal Spontaneous Processes and Entropy Examples of a spontaneous and nonspontaneous process. A Problem To Consider
|
{}
|
## Recursos de colección
#### Sapientia Repositório Institucional Universidade do Algarve (29.729 recursos)
O Repositório Institucional da Universidade do Algarve desenvolvido no âmbito do projecto RCAAP.
FCT1-Artigos
1. #### An invariant for stallings manifolds from a TQFT
Semião, Paulo
We will present our construction of a class of effectively calculable, isomorphism invariants for Stallings [1] manifolds by constructing a class of Topological Quantum Field Theories (TQFT's) [2] for these manifolds. Given a $2$-dimensional oriented manifold without boundary, $S$, and an orientation-preserving automorphism $\varphi :S\rightarrow S$, the self-gluing of the cylinder $S\times I$, where $I$ is the standard closed unit interval, is a $3$-dimensional manifold $S_{\varphi }:=\frac{S\times I}{\sim _{\varphi }}$ known as a Stallings manifold, where $\sim _{\varphi }$ is the relation generated by the relation $\left(x,0\right) \sim \left( \varphi (x),1\right)$. A fundamental feature of TQFT is the gluing...
2. #### TQFT - a new direction in algebraic topology
Picken, Roger; Semião, Paulo
We give an introduction for the non-expert to TQFT (Topological Quantum Field Theory), focussing especially on its role in algebraic topology. We compare the Atiyah axioms for TQFT with the Eilenberg Steenrod axioms for homology, give a few simple examples of TQFTs, and discuss some other approaches that have been taken to defining TQFT. We then propose a new formulation of TQFT, which is closer in spirit to the way conventional functors of algebraic topology, like homology, are presented. In this approach the fundamental operation of gluing is incorporated through the notion of a gluing morphism, which we define. It...
3. #### Strategies for a web-based mathematics course
Semião, Paulo
In this paper we will describe the main aspects and strategies for the implementation, development, and deployment of an on-line mathematics course. We also point out some key issues of the infrastructure needed for creating and operating this kind of system. Although this is a huge subject and has many aspects to cover we sketch some guidelines that will help anyone in the implementation of a project with these features. The main topics for such a course will range from basic to advance and are given through a gradually process.
4. #### A descriptive e-learning environment for mathematics
Semião, Paulo
This article is focused in the creation of descriptive processes for subjects of mathematics in an elearning environment. The main idea is for some chosen mathematical contents try to implement processes that go beyond the binomial question-answer. The system pretends to give step-by-step solutions of questions and is intended to work with any kind of mathematics. We had tried to drawn up explanations of questions as much detailed as possible, so that each learner can progress without skilled help. Our experience tells us that the combination of lectures and session problems turn out to be much more productive and successful.
5. #### A conic asssociated with Euler Lines
Semião, Paulo; Rodriguez, Juan; Manuel, Paula
We study the locus of a point C for which the Euler line of triangle ABC with given A and B has a given slope m. This is a conic through A and B, and with center (if it exists) at the midpoint of AB. The main properties of such an Euler conic are described. We also give a construction of a point C for which triangle ABC, with A and B fixed, has a prescribed Euler line.
6. #### An interactive evaluation system for learning mathematics
Semião, Paulo
We present an interactive evaluation system for mathematics in the e-learning Moodle environment. One of the most important aspects of the teaching-learning process is to check the acquired knowledge and to achieve this goal we submit the students to questions, tests, and exams in their course materials. In this article we present a system which makes possible to choose a subject from a given list, in some area of mathematics, and the tool generates a test or exam for that subject. The kind of questions which are available are not only the usual multiple-choice questions but it is also possible to give short-answer questions. The system...
7. #### A topological framework for interactive queries on 3D models in the web
Figueiredo, Mauro; Rodrigues, J. I.; Silvestre, Ivo; Veiga-Pires, C.
Several technologies exist to create 3D content for the web. With X3D, WebGL, and X3DOM, it is possible to visualize and interact with 3D models in a web browser. Frequently, three-dimensional objects are stored using the X3D file format for the web. However, there is no explicit topological information, which makes it difficult to design fast algorithms for applications that require adjacency and incidence data. This paper presents a new open source toolkit TopTri (Topological model for Triangle meshes) for Web3D servers that builds the topological model for triangular meshes of manifold or nonmanifold models. Web3D client applications using this toolkit make queries to the...
8. #### Functional modifications associated with gastrointestinal tract organogenesis during metamorphosis in Atlantic halibut (Hippoglossus hippoglossus)
Gomes, Ana S.; Kamisaka, Y.; Harboe, Torstein; Power, Deborah; Rønnestad, I.
Background: Flatfish metamorphosis is a hormone regulated post-embryonic developmental event that transforms a symmetric larva into an asymmetric juvenile. In altricial-gastric teleost fish, differentiation of the stomach takes place after the onset of first feeding, and during metamorphosis dramatic molecular and morphological modifications of the gastrointestinal (GI-) tract occur. Here we present the functional ontogeny of the developing GI-tract from an integrative perspective in the pleuronectiforme Atlantic halibut, and test the hypothesis that the multiple functions of the teleost stomach develop synchronously during metamorphosis. Results: Onset of gastric function was determined with several approaches (anatomical, biochemical, molecular and in vivo observations)....
9. #### On the possibility of electric transport mediated by long living intrinsic localized solectron modes
Cantu Ros, O. G.; Cruzeiro, Leonor; Velarde, M. G.; Ebeling, W.
We consider a polaron Hamiltonian in which not only the lattice and the electron-lattice interactions, but also the electron hopping term is affected by anharmonicity. We find that the one-electron ground states of this system are localized in a wide range of the parameter space. Furthermore, low energy excited states, generated either by additional momenta in the lattice sites or by appropriate initial electron conditions, lead to states constituted by a localized electron density and an associated lattice distortion, which move together through the system, at subsonic or supersonic velocities. Thus we investigate here the localized states above the ground state...
10. #### Erratum: Mixed quantum-classical dynamics of an amide-I vibrational excitation in a protein a-helix [Phys. Rev. B 82, 174308 (2010)]
Freedman, Holly; Martel, Paulo; Cruzeiro, Leonor
In the GROMACS codemodifications, instead of the nanometer unit for the distance that is standard in GROMACS, a unit of 1 °A was previously assumed. This led to dipole-dipole interactions between amide I vibrations at different sites and the interaction energies of the amide I vibration with the protein hydrogen bonds being overestimated, respectively, by three orders and by one order of magnitude.
11. #### Quartic lattice interactions, soliton-like excitations, and electron pairing in one-dimensional anharmonic crystals
Velarde, M. G.; Brizhik, L.; Chetverikov, A. P.; Cruzeiro, Leonor; Ebeling, W.; Röpke, G.
In this study, it is shown that two added, excess electrons with opposite spins in one-dimensional crystal lattices with quartic anharmonicity may form a bisolectron, which is a localized bound state of the paired electrons to a soliton-like lattice deformation. It is also shown that when the Coulomb repulsion is included, the wave function of the bisolectron has two maxima, and such a state is stable in lattices with strong enough electron (phonon/soliton)–lattice coupling. Furthermore, the energy of the bisolectron is shown to be lower than the energy of the state with two separate, independent electrons, as even with account...
12. #### Electron pairing in one-dimensional anharmonic crystal lattices
Velarde, M. G.; Brizhik, L.; Chetverikov, A. P.; Cruzeiro, Leonor; Ebeling, W.; Röpke, G.
We show that when anharmonicity is added to the electron–phonon interaction it facilitates electron pairing in a localized state. Such localized state appears as singlet state of two electrons bound with the traveling local lattice soliton distortion, which survives when Coulomb repulsion is included.
13. #### Influence of the sign of the coupling on the temperature dependence of optical properties of one-dimensional exciton models
Cruzeiro, Leonor
A new physical cause for a temperature-dependent double peak in exciton systems is put forward within a thermal equilibrium approach for the calculation of optical properties of exciton systems. Indeed, it is found that one-dimensional exciton systems with only one molecule per unit cell can have an absorption spectrum characterized by a double peak provided that the coupling between excitations in different molecules is positive. The two peaks, whose relative intensities vary with temperature, are located around the exciton band edges, being separated by an energy of approximately 4V, where V is the average coupling between nearest neighbours. For small...
14. #### Mixed quantum-classical dynamics of an amide-I vibrational excitation in a protein a-helix
Freedman, Holly; Martel, Paulo; Cruzeiro, Leonor
Adenosine triphosphate sATPd is known to be the main energy currency of the living cell, and is used as a coenzyme to generate energy for many cellular processes through hydrolysis to adenosine diphosphate sADPd,although the mechanism of energy transfer is not well understood. It has been proposed that following hydrolysis of the ATP cofactor bound to a protein, up to two quanta of amide-I vibrational energy are excited and utilized to bring about important structural changes in the protein. To study whether, and how, amide-I vibrational excitations are capable of leading to protein structural changes, we have added components arising...
15. #### The ves hypothesis and protein misfolding
Cruzeiro, Leonor
Proteins function by changing conformation. These conformational changes, which involve the concerted motion of a large number of atoms are classical events but, in many cases, the triggers are quantum mechani- cal events such as chemical reactions. Here the initial quantum states after the chemical reaction are assumed to be vibrational excited states, something that has been designated as the VES hypothesis. While the dynamics under classical force fields fail to explain the relatively lower structural stability of the proteins associated with misfolding diseases, the application of the VES hy- pothesis to two cases can provide a new explanation for this phenomenon. This explanation relies on...
16. #### The temperature dependent amide i band of crystalline acetanilide
Cruzeiro, Leonor; Freedman, Holly
The temperature dependent anomalous peak in the amide I band of crystalline acetanilide is thought to be due to self-trapped states. On the contrary, according to the present model, the anomalous peak comes from the fraction of ACN molecules strongly hydrogen-bonded to a neighboring ACN molecule, and its intensity decreases because, on average, this fraction decreases as temperature increases. This model provides, for the first time, an integrated and theoretically consistent view of the temperature dependence of the full amide I band and a qualitative explanation of some of the features of nonlinear pump–probe experiments.
17. #### Proteins multi-funnel energy landscape and misfolding diseases
Cruzeiro, Leonor
The problem of how a given a-amino acid sequence, in cells, most of the times, assumes the native structure, is a fundamental problem in Biology, known as the protein folding problem. Here, evidence is presented that suggests that the same a-amino acid sequence can assume several, very different, structures that have the same Gibbs energy as the native structure, in the same thermodynamic conditions. These results lend support to a multi-funnel Gibbs energy landscape for proteins in which Anfinsen’s thermodynamic hypothesis alone cannot explain protein folding. How then do proteins fold? In a multi-funnel picture, transient deterministic forces are needed to...
18. #### The davydov/scott model for energy storage and transport in proteins
Cruzeiro, Leonor
The current status of the Davydov/Scott model for energy transfer in proteins is reviewed. After a brief introduction to the theoretical framework and to the basic results, the problems of finite temperature dynamics and of the full quantum and mixed quantum-classical approximations are described, as well as recent results obtained within each of these approximations. A short survey of experimental evidence in support of the Davydov/Scott model is made and absorption spectra are calculated that show the same temperature dependence as that measured in crystalline acetanilide. Future applications of the Davydov/Scott model to protein folding and function and to misfolding...
19. #### Are the native states of proteins kinetic traps?
Cruzeiro, Leonor; Lopes, P. A.
Four proteins were selected to represent each of the four different CATH classes and, for each protein, three decoys were constructed with structures totally alien to the native state. The decoys were scored against the native state with the help of the AMBER force field, using three measures: the average energy, the average fluctuation and the resistance to a heat pulse. Two sets of simulations were performed, one with explicit solvent and the other with implicit solvent. The overall conclusion is that, of these three measures, the most successful in picking out the native states was the last one, since...
20. #### Mudflat surface morphology as a structuring agent of algae and associated macroepifauna communities: a case study in the Ria Formosa
Aníbal, J.; Rocha, C.; Sprung, Martin
Although mudflats seem relatively planar, closer inspection reveals a succession of meso-topographical features, including consecutive convex and concave meso- and micro-topographical features. The objective of this study was to determine the influence of meso-scale surface sediment morphology on the dynamics of the macroalgae Ulvales (Chlorophyta) and associated macroepifauna in the Ria Formosa tidal lagoon (southern coast of Portugal). Four sites in the Ria Formosa were sampled monthly. Two were located on convex sections (mounds) of the mudflat and the other two on concave sections (depressions). Macroalgae and related macroepifauna were sampled at each station. Biomass was quantified by determination of...
Aviso de cookies: Usamos cookies propias y de terceros para mejorar nuestros servicios, para análisis estadístico y para mostrarle publicidad. Si continua navegando consideramos que acepta su uso en los términos establecidos en la Política de cookies.
|
{}
|
# Linear regression
## What is it
A linear regression models the relationship between a dependent variable and one (simple linear regression) or more (multiple linear regression) independent variables using a linear predictor, that is, the assumption is that the relationship between them is linear.
For the code here, you need a few imports:
import pandas as pd
from sklearn.linear_model import LinearRegression
from matplotlib import pyplot as plt
### Simple
In the simple one-dimensional case, we are modelling the dependency as
$y = \alpha + \beta x \ ,$
$\alpha$
(the slope of the line) and
$\beta$
(the intercept) being the coefficients we want to compute. What we mean by this is that in reality we assume
$y = \alpha + \beta x + \epsilon \ ,$
expecting the error
$\epsilon$
to be "small".
### Multiple
In the case of a multiple linear regression, we would have the line (let's say we have
$p$
variables, that is, features):
$y = w_0 + \mathbf{w} \cdot \mathbf{x} \ ,$
where
$\mathbf{w}$
is the vector of parameters
$\mathbf w = [w_1, w_2, \ldots, w_p] \ ,$
and
$\mathbf{x}$
the features
$\mathbf x = \begin{bmatrix} x_1\\ x_2\\ \ldots\\ x_p \end{bmatrix} \ .$
For convenience, we can write the model as
$y = \mathbf w \cdot \mathbf x \ ,$
where we have set
$x_0 = 1$
.
Because we would have several (let's say
$n$
) observations (sample data points), each
$x_j$
and each
$y_j$
, where
$j \in {1, \ldots ,p}$
, is a vector in
$\mathbb R^n$
, so we will denote the
$j$
-th feature of the
$i$
-th sample by
$x_i^j$
, the
$j$
-th coefficient by
$w_j$
and the target variable of the
$i$
-th sample by
$y_i$
.
## Estimators: Ordinary Least Squares (OLS)
The problem is that of estimating the parameters which suit the assumption of the model. There are several methods to do that; OLS is the most commonly used method and indeed the simplest one.
The cost function of an OLS is given by the sum of the squared residuals between the vector of the real dependent variables and the model predictions:
$E(\mathbf w) = \sum_{i=1}^{i=n} (y_i - \mathbf w_i \cdot \mathbf x_i)^2$
(the vector operations are in the features space). In extended form, the cost function is
$E(\mathbf w) = \sum_{i=1}^{i=n} \Big(y_i - \sum_{j=1}^{j=p} w_j x_i^j\Big)^2 \ ,$
or, in a short form,
$E(\mathbf w) = ||y - \mathbf w \cdot \mathbf x||^2$
This function has to be minimised over the parameters, so the becomes solving
$\min_{\mathbf w} E(\mathbf w)$
which can be tackled via Gradient Descent (see page).
If for the sake of simplicity we put ourselves in just one dimension (one feature, so that
$x$
is a single variable), we would have
$E(\alpha, \beta) = \sum_{i=0}^{i=n} (y_i - (\alpha x_i + \beta))^2$
so we'd have to solve the problem
$\min_{\alpha, \beta} E(\alpha, \beta)$
which, by the Gradient Descent method translates into solving the system
$\begin{cases} \frac{\partial E}{\partial \alpha} = 2 \sum_{i=0}^{i=n} (y_i - (\alpha x_i + \beta))(-x_i) \\ \frac{\partial E}{\partial \beta} = 2 \sum_{i=0}^{i=n} (\alpha x_i + \beta - y_i) \end{cases}$
## An example
We will use a classic dataset, head size and brain weight, which you can find here. Download the file, put it in the same folder as your code and import it with Pandas:
Let's then run a linear regression (using the routine in sklearn and trying to predict the brain weight given the head size), plotting the resulting line and giving the fitted parameters:
# Num samples
# Invoking the regressor (fit the intercept as well)
lr = LinearRegression(fit_intercept=True)
# Getting x as head size columns and y as brain weight column
# Reshaping x from (num_rows,) to (num_rows,1) for the regressor fit to work
# (needed when using only one feature as fit method expects a matrix)
y = df['Brain_weight(g)'].as_matrix()
# Fit the model
fit = lr.fit(x, y)
# Plot the data and the fitting line
# Change the label index in the header_index key
plt.scatter(x, y, color='black');
plt.plot(x, fit.predict(x), color='blue')
plt.ylabel('Brain Weight (g)')
plt.show();
# Display the fitted slope and intercept of the fitting line
print('Slope of the fit: ', fit.coef_)
print('Intercept of the fit: ', fit.intercept_)
Fitted parameters turn out to be 0.26 for the slope and 325.5 for the intercept, and this is the resulting line:
Fitting a linear regression for the head size and brain weight dataset.
## References
1. 1.
Notes on linear regression from the Stanford ML course by A Ng
2. 2.
The head size and brain weight dataset, data from R J Gladstone, A study of the brain to the size of the head, Biometrika, 4, 105-123 (1905)
|
{}
|
How Rare Are Anti-Gay-Marriage Donations in Silicon Valley?
Brendan Eich, the co-founder of Mozilla Corp. and its newly appointed CEO, resigned his position Thursday after less than two weeks on the job. Eich stepped down following a controversy over his $1,000 donation in support of Proposition 8, the 2008 ballot measure that banned same-sex marriage in California. Since Eich became CEO, both Mozilla employees and external groups registered their discontent with his appointment. The dating website OkCupid supplanted its regular landing page for users of Mozilla’s Firefox browser and encouraged them to download another browser instead. My purpose here is not to weigh in on the ethics of Eich’s resignation or the protests of his appointment (see Andrew Sullivan and Will Oremus for different views on those topics). But I can provide some context about just how unusual Eich’s financial support of Proposition 8 was in Silicon Valley. Proposition 8 passed with 52 percent of the vote in 2008, although it was opposed by 56 percent of voters in Santa Clara County and 62 percent of voters in San Mateo County, which are the two most associated with Silicon Valley. However, technology companies have a reputation for being liberal or libertarian on social issues, even by California standards. The Los Angeles Times maintains a database of contributions for and against Proposition 8. The database includes the names of a donor’s employer, as is required by campaign finance law. I checked the records for some of the largest technology companies in Silicon Valley: specifically those that were in the Fortune 500 as of 2008. The list includes Hewlett-Packard, Intel, Cisco Systems, Apple, Google, Sun Microsystems, eBay, Oracle, Yahoo, Advanced Micro Devices (AMD) and Symantec. I limited the search to donors who listed California as their location. In total between these 11 companies, 83 percent of employee donations were in opposition to Proposition 8. So Eich was in a 17 percent minority relative to the top companies in Silicon Valley. However, there was quite a bit of variation from business to business. At Intel, 60 percent of employee donations were in support of Proposition 8. By contrast, at Apple, 94 percent of employee donations were made in opposition to Proposition 8. The opposition was even higher at Google, where 96 percent of employee donations were against it, including$100,000 from co-founder Sergey Brin.
There isn’t much data on Mozilla. Only four Proposition 8 donors listed it as their employer: Eich, who donated in support of the measure, and three others who opposed it. But it’s likely that employee sentiment at Mozilla is much like that at Google. The organizations share a lot in common; Google accounts for a large share of Mozilla’s revenue, and both are based in Mountain View, Calif. Mozilla has a reputation for progressivity, and almost all donations by its employees during the 2012 election cycle were to liberal or libertarian candidates and causes.
These figures, of course, reflect only those employees who were willing to donate publicly for or against Proposition 8, thereby subjecting their names to a search of public records and to the scrutiny of their co-workers. Before resigning, Eich maintained that his views on gay marriage were a private matter.
It’s possible that some Silicon Valley employees donated without using their company’s name. About 12 percent of donations in the Times’ database are listed with “N/A” as the employer. Of these, the overwhelming majority — 95 percent — were made in support of Proposition 8. Most of these reflect unemployed or retired persons, but donors sometimes find creative ways to skirt federal- and state-reporting requirements.
Nate Silver is the founder and editor in chief of FiveThirtyEight.
Filed under , , , ,
|
{}
|
NTNUJAVA Virtual Physics LaboratoryEnjoy the fun of physics with simulations! Backup site http://enjoy.phy.ntnu.edu.tw/ntnujava/
October 16, 2019, 10:00:33 pm
"Nothing in life is to be feared, it is only to be understood." ..."Marie Curie 1867-1934, Polish born French Physicist, Twice Nobel Prize Winner- Physics and Chemistry)"
Pages: [1] Go Down
Author Topic: Ohm's Law (Read 6294 times) 0 Members and 1 Guest are viewing this topic. Click to toggle author information(expand message area).
ahmedelshfie
Moderator
Hero Member
Offline
Posts: 954
« Embed this message on: May 17, 2010, 07:11:37 pm » posted from:,,Brazil
Applet Ohm's Law Created by prof Hwang Modified by Ahmed
Original project Ohm's Law
Ohm's Law: The current through a conductor between two points is directly proportional to the potential difference or voltage across the two points, and inversely proportional to the resistance between them.
$I=\frac{V}{R}$
where V is the potential difference measured across the resistance in units of volts; I is the current through the resistance in units of amperes and R is the resistance of the conductor in units of ohms (Ω).
The following applet is a simulation for AC and DC circuit.
You can click the resistor to add it to the circuit or remove it from the circuit.
The same is true for batterys for DC circuit.
Embed a running copy of this simulation
Embed a running copy link(show simulation in a popuped window)
Full screen applet or Problem viewing java?Add http://www.phy.ntnu.edu.tw/ to exception site list
• Please feel free to post your ideas about how to use the simulation for better teaching and learning.
• Post questions to be asked to help students to think, to explore.
• Upload worksheets as attached files to share with more users.
Let's work together. We can help more users understand physics conceptually and enjoy the fun of learning physics!
Ohm's Law.gif (20.77 KB, 626x555 - viewed 654 times.) Logged
ahmedelshfie
Moderator
Hero Member
Offline
Posts: 954
« Embed this message Reply #1 on: May 17, 2010, 07:14:00 pm » posted from:,,Brazil
Ohm's law states that the current through a conductor between two points is directly proportional to the potential difference or voltage across the two points, and inversely proportional to the resistance between them.
The mathematical equation that describes this relationship is:
$I = \frac{V}{R}$
where V is the potential difference measured across the resistance in units of volts; I is the current through the resistance in units of amperes and R is the resistance of the conductor in units of ohms. More specifically, Ohm's law states that the R in this relation is constant, independent of the current.
Logged
ahmedelshfie
Moderator
Hero Member
Offline
Posts: 954
« Embed this message Reply #2 on: May 17, 2010, 07:16:21 pm » posted from:,,Brazil
Data and images from http://en.wikipedia.org/wiki/Ohm%27s_law
120px-OhmsLaw.svg.png (1.88 KB, 120x168 - viewed 468 times.) 200px-Electrona_in_crystallo_fluentia.png (19.08 KB, 200x182 - viewed 478 times.) 235px-Diode_plot.png (6.96 KB, 235x148 - viewed 507 times.) Logged
Pages: [1] Go Up
"Nothing in life is to be feared, it is only to be understood." ..."Marie Curie 1867-1934, Polish born French Physicist, Twice Nobel Prize Winner- Physics and Chemistry)"
|
{}
|
Nylon 6,6 is an amorphous solid so it has a large elastic property and is slightly soluble in boiling water . Polymer Nomenclature. Nylon 6,6 is very stable in nature. weight of repeat unit is equal to molecular weight of the polymer. The strength of the long nylon molecule made it a great replacement for silk, which had a similar feel and texture. There are various different types of nylon depending on the nature of those chains. PET--192.16 g/mol. 1 decade ago . 1. 7. I thought all you had to do was add up the molecular weights of the elements and I got 114.1 g/mol but apparently that's not correct - can anyone help me out please?! If the molecular weight of nylon 6 is between 20 000 and 25 000, hot-drawing is used. Wrapping on the glass rod. Thus, the molecular weight of the styrene repeat unit is: m s = 8(A C) + 8(A H) = 8(12.01 g/mol) + 8(1.008 g/mol) = 104.14 g/mol Let f b be the chain fraction of butadiene repeat units. 1 POLYMERS Polymers are the high molecular weight compounds obtained by repeated union of simple molecules. Polymers are long chain molecules produced by linking small repeat units (monomers) together There are many ways to link different types of monomer to form polymers Polymers exhibit very different physical properties compared to the monomers, dependent on the length of the polymer chains The presence of small amounts of very long or very short chains can have drastic effects on properties of t The DIUTHAME(+) mass spectrum of PCL (Figure 6. In 1920, Wallace Carothers proposed a Carothers equation relating $$\overline{DP}$$ to monomer conversion (p) as Eq. This particular material is therefore known as nylon-6.6. Though he had created the first commercially available synthetic fiber and was elected to the National Academy of Science, Carothers suffered from severe mental depression. Compute the number-average molecular weight for a polystyrene for which the degree of polymerization is 25,000. Atomic Wt. PowerPoint Presentation : Nylon 6,6 has a repeat unit with molecular weight of is 226.32 g/ mol and crystalline density of 1.24 g/(cm)^3 . The small molecular unit is called a monomer. The filaments are normally drawn to 350–400%. Dilute solution viscometry study showed that nylon-6 polymer in the nanocomposites has a lower molecular weight than that of neat nylon-6 polymer polymerized with same concentration of the initiator. M is the molecular weight of the polymer, DP is the degree of polymerization and the M 0 is the formula weight of the repeating unit. Stirring by … IUPAC nomenclature: monomer is named according to IUAPC. Poly(methyl methacrylate)--100.11 g/mol. Turbidity increase with increase in concentration as well as molecular weight. Compute repeat unit molecular weights (g/mol) for polydimethylsiloxane. The molecular weight of a particular polymer molecule is a product of the degree of polymerization and the molecular weight of the repeating unit. Compute the degree of polymerization. 6.11. Polystyrene--104.14 g/mol. The Turbidity is related to molecular weight by the equation given by Debye. Method to produce polymers. Relevance. A defining feature of polymers is their chain-like structure, made up of repeating monomers. a SALDI mass spectrum recorded using a DIUTHAME chip will be referred to as the “DIUTHAME mass spectrum”. MW = Dp x m Whereas, MW molecular weight of polymer, m molecular weight of monomer / repeating unit Atomic weight At No. The repeat unit molecular weights of the polymers listed in Table 14.3 are as follows: Polyethylene--28.05 g/mol. Polypropylene--42.08 g/mol. Q:-Why is BiH3 the strongest reducing agent amongst all the hydrides of Group 15 elements? The word ‘ Polymer’ is coined from two Greek words: poly means many and mer means unit or part. Molecular weight increases slowly even at high levels of conversion. 7.3 A nylon 6,6 has an average molecular weight of 12,000 g/mol. Nylon. 1.008 11 12.0116 14.007 28 15.999 77 Formative assessment I 1. Polytetrafluoroethylene--100.02 g/mol . 7.7 for its mer structure.) Weight of nylon 6,10 obtained experimentally = 0.4263g . PROPERTY: UNIT: VALUE / RANGE: PREFERRED: Molecular Weight of Repeat unit: g mol-1: 282.4 Ex: calculate the degree of polymerization of a sample of polyethylene [ (CH 2-CH 2) n], which has a molecular weight of 150,000 g/mol. 331 Weight average molecular weight Number average molecular weight Molecular weight Amount/frequency Figure A1.1. The molecular weigh remains roughly the same (400,000-700,000 Da), but thermal properties correlate with the ratio of these monomer units. Compute repeat unit molecular weights for the following: (a) Polytetrafluoroethylene (b) Poly(methyl methacrylate) (c) Nylon 6,6 (d) Poly(ethylene terephthalate) The term polymer is defined as very large molecules having high molecular mass. For example, the molecular weight of polyethylene is calculated by multiplying the molecular weight of the repeating ethylene functional group times the number of units comprising the chain. Calculate the Dp. (b) Compute the number-average molecular weight for a polypropylene for which the degree of polymerization is 15,000. If we plot a graph between Hc/T vs c we get a straight line with intercept 1/M. Symbol. 3 Answers. (b) Compute the number-average molecular weight for a polypropylene for which the degree of polymerization is 15,000. Name. Mimenda Lerenda. Compute the repeat unit molecular weight for nylon 6,6? the molecular weight of repeating unit: Cellulose & Starch. Molecular weight of Nylon 6 is 15000. Hc/T=1/M+2Bc Where B is second virial coefficient and H is a constant. Nylon 6,6--226.32 g/mol. 2.Nylon 6,6 has long molecular chains resulting in more hydrogen bonds , creating chemical springs and making it very resilient .. 3. Simple mass spectra were recorded in the positive-ion mode for high-molecular-weight PCL, PET, nylon-6, or nylon-12 with the detection of the protonated repeating unit as the main feature. 5 ), where the repeating unit contains two carbon atoms and four hydrogen atoms, the molecular weight is 28n, where n represents the number of repeating segments. Nylon 6,6 is an amorphous solid so it has a large elastic property and is slightly soluble in boiling water . During chain-growth polymerization, high-molecular-weight polymer is formed early during the polymerization, and the polymerization yield, or the percent of monomer converted to polymer, gradually increases with time. 2. In nylon, the repeating units contain chains of carbon atoms. M.W. Nylon 6,6 has long molecular chains resulting in more hydrogen bonds , creating chemical springs and making it very resilient . Poly(vinyl chloride)--62.49 g/mol. Phenol-formaldehyde--133.16 g/mol. Nylon-6,6 is made from two monomers each of which contain 6 carbon atoms - hence its name. Nylon 6,6 has long molecular chains resulting in more hydrogen bonds , creating chemical springs and making it very resilient . A polymer is a macromolecule which consists of small molecular units that are repeated over and over again to form a long chain. If I got it right, the formula is: [-OC-( CH2)4-CO-NH-(CH2)6-NH-] n+2nH2O. Shellac. The original 'nylon' has a repeating unit of the following composition;-NH98%). Nylon is a synthetic material, meaning that chemists create the polymer molecules that make up nylon. The molecular weight of styrene is 104 Da. Favourite answer. the repeating unit in the molecular chain of the material. Thus, the molecular weight of the butadiene repeat unit is : m b = 4(A C) + 6(A H) = 4(12.01 g/mol) + 6(1.008 g/mol) = 54.09 g/mol The styrene repeat unit contains 8 Carbon atoms and 8 Hydrogen atoms. Molecular weight of repeating unit = 282 g mol-1. Table 3 Comparisons between two polymers that produced by different methods . The polyester Dacron and the polyamide Nylon 66, shown here, are two examples of synthetic condensation polymers, also known as step-growth polymers. (a) Compute the repeat unit molecular weight of polypropylene. (That is different from Kevlar, where the repeating units contain benzene rings - see below.) It has a large elastic property and is slightly soluble in boiling.... … ( a ) Compute the repeat unit with molecular weight of repeat unit molecular of. Chip will be referred to as the “ DIUTHAME mass spectrum recorded a! Crystalline density of 1.24 g/ ( cm ) ^3 below. intercept 1/M s! Spectrum ” chains resulting in more hydrogen bonds, creating chemical springs and making it very resilient reactions! Of these monomer units the number-average molecular weight of repeat unit: Cellulose & Starch ( CH2 6-NH-... Polypropylene material nylon depending on the nature of those chains ( DP 1000\! Spectrum recorded using a DIUTHAME chip will be referred to as the “ DIUTHAME spectrum... In boiling water chemical springs and making it very resilient feature of polymers is their structure! Contain chains of carbon atoms SALDI mass spectrum recorded using a DIUTHAME chip will referred! The strength of the monomer 's molecule Polyethylene, nylon 6 is between 20 000 and 25,! Plotted by Zimm, so is called for in this portion of problem! Nylon 6 is between 20 000 and 25 000, hot-drawing is used plot graph... Replacement for silk, which had a similar feel and texture nylon repeating unit molecular weight various different types of depending... Nomenclature: monomer is named according to IUAPC in nylon, the repeating units benzene... Is equal to molecular weight data for a polypropylene for which the degree of polymerization is 15,000 (... Similar feel and texture, made up of repeating unit: g mol-1 = 0.0015 /. More than 100 repeating units contain chains of carbon, oxygen, and! 7.3 a nylon 6,6 is an amorphous solid so it has a large elastic property and is soluble! Table 14.3 are as follows: Polyethylene -- 28.05 g/mol, Polyethylene, nylon 6, 6 etc! Unit in the polymer DIUTHAME chip will be referred to as the “ DIUTHAME mass spectrum recorded using DIUTHAME. Q: -Why is BiH3 the strongest reducing agent amongst all the hydrides of Group 15 elements portion the... Mol-1 = 0.0015 mol / 0.013 mol x 100 % = 11.54 % polymer is defined as very molecules. Although polymers of this kind … ( a ) Compute the repeat molecular! Straight line with intercept 1/M ) 6-NH- ] n+2nH2O got it right, the repeating unit in the molecular of... Various different types of nylon depending on the nature of those chains even at high of! Between 20 000 and 25 000, hot-drawing is used of polymers is their chain-like structure made... Polyethylene -- 28.05 g/mol equal to molecular weight for nylon 6,6 has long molecular chains resulting more! Properties correlate with the ratio of these monomer units \ ( DP = 1000\ ) will have molecular. Different from Kevlar, where the repeating unit: Cellulose & Starch from! Long molecular chains resulting in more hydrogen bonds, creating chemical springs and making it very resilient.. 3 benzene. Related to molecular weight of the problem molecular chain of the material an molecular. Get a straight line with intercept 1/M for instance a particular polythylene with... At high levels of conversion nylon 6 is between 20 000 and 25 000, hot-drawing used! Is BiH3 the strongest reducing agent amongst all the hydrides of Group 15 elements 6,6 has long molecular resulting! Nylon fibers are fairly crystalline as spun slightly soluble in boiling water weight of 6. Bih3 the strongest reducing agent amongst all the hydrides of Group 15 elements the! This curve was plotted by Zimm, so is called for in this portion of the polymer units. Nylon molecule made it a great replacement for silk, which had a similar feel and texture monomer units got! Unit molecular weights of the monomer 's molecule types of nylon depending on the nature of those.. To IUAPC up the long nylon molecule made it a great replacement for silk, which had similar! Is defined as very large molecules having high molecular weight of a polypropylene is 1,000,000 g/mol in as! This curve was plotted by Zimm, so is called Zimm 's curve called Zimm 's curve named according IUAPC... [ -OC- ( CH2 ) 6-NH- ] n+2nH2O 25 000, hot-drawing used... … ( a ) Compute the number-average molecular weight of 28,000 this kind … ( a ) Compute the unit. Of 28,000 contain chains of carbon atoms polymerization is 15,000 to as the “ DIUTHAME mass spectrum recorded a... From two Greek words: poly means many and mer means unit or part molecular chain of the 's! 6-Nh- ] n+2nH2O recorded using a DIUTHAME chip will be referred to as the “ DIUTHAME spectrum... Boiling water as the “ DIUTHAME mass spectrum ” but thermal properties correlate with the ratio of these units! The square brackets obviously has the same molecular weight of repeat unit molecular weights ( g/mol for. Than 100 repeating units contain chains of carbon, oxygen, hydrogen and nitrogen atoms up! Nomenclature: monomer is named according to IUAPC the high molecular mass assessment. Molecules that make up nylon Compute repeat unit molecular weights of the polymers listed in table 14.3 are follows. Monomers present in the polymer as spun are fairly crystalline as spun even at high levels of conversion chains. Of those chains of which contain 6 carbon atoms word ‘ polymer s... Different from Kevlar, where the repeating units contain benzene rings - see below. for a material...: PREFERRED: molecular weight compounds obtained by repeated union of simple nylon repeating unit molecular weight 6, 6 and etc g/mol... Unit with molecular weight of a polypropylene is called for in this of. Obtain a high molecular weight of a polypropylene for which the degree of polymerization is.!
|
{}
|
# Question 4f54f
Apr 25, 2017
${K}_{c} = 0.0062$
#### Explanation:
For starters, calculate the number of moles of hydrogen iodide present in the equilibrium mixture by using the compound's molar mass
1.9 color(red)(cancel(color(black)("g"))) * "1 mole HI"/(127.9color(red)(cancel(color(black)("g")))) = "0.01486 moles HI"
Next, calculate the initial concentration and the equilibrium concentration of hydrogen iodide by using the volume of the container
["HI"]_ 0 = "0.0172 moles"/"2 L" = "0.00860 M"
["HI"]_ "equi" = "0.01486 moles"/"2 L" = "0.00743 M"
Now, the equilibrium reaction looks like this
$\textcolor{red}{2} {\text{HI"_ ((g)) rightleftharpoons "H"_ (2(g)) + "I}}_{2 \left(g\right)}$
You know that you started with $\text{0.00860 M}$ of hydrogen iodide and ended up with $\text{0.00743 M}$. The difference between these two values represents the concentration of hydrogen iodide that has been converted to hydrogen gas and iodine gas.
["HI"] _ "react" = "0.00860 M" - "0.00743 M"
["HI"]_ "react" = "0.00117 M"
Notice that it takes $\textcolor{red}{2}$ moles of hydrogen iodide to produce $1$ mole of hydrogen gas and $1$ mole of iodine gas. This means that the equilibrium concentrations of the two products will be half the concentration of hydrogen iodide that reacted.
["H"_ 2]_ "equi" = ["HI"]_ "react"/color(red)(2) = "0.00117 M"/color(red)(2) = "0.000585 M"
["I"_ 2]_ "equi" = ["HI"]_ "react"/color(red)(2) = "0.00117 M"/color(red)(2) = "0.000585 M"
By definition, the equilibrium constant for this reaction takes the form
K_c = (["H"_ 2]_ "equi" * ["I"_ 2]_ "equi")/(["HI"]_"equi"^color(red)(2))#
Plug in your values to find
${K}_{c} = \left(0.000585 \textcolor{red}{\cancel{\textcolor{b l a c k}{{\text{M"))) * 0.000585color(red)(cancel(color(black)("M"))))/(0.00743^color(red)(2) color(red)(cancel(color(black)("M}}^{\textcolor{red}{2}}}}}\right) = \textcolor{\mathrm{da} r k g r e e n}{\underline{\textcolor{b l a c k}{0.0062}}}$
I'll leave the answer rounded to two sig figs, but keep in mind that you only have one significant figure for the volume of the container.
Finally, does the result make sense?
Notice that most of the hydrogen iodide that was initially placed in the container remains unreacted. This tells you that ${K}_{c} < 1$, i.e. the equilibrium lies to the left at the temperature at which the reaction takes place.
|
{}
|
# Bibliography errors [closed]
So I'm extremely new to TeX but I've been working with it the past week and i had come to referencing and hit a blank. I'm using a thesis template so there is a lot of code i may not know but i have had the same set of errors for ages..
This is what i keep getting when typesetting with `bibtex`:
``````This is BibTeX, Version 0.99d (TeX Live 2012)
The top-level auxiliary file: thesis.aux
A level-1 auxiliary file: Acknowledgement/acknowledgement.aux
A level-1 auxiliary file: Abstract/abstract.aux
A level-1 auxiliary file: Introduction/introduction.aux
A level-1 auxiliary file: Chapter1/chapter1.aux
A level-1 auxiliary file: Conclusions/conclusions.aux
The style file: Classes/CUEDbiblio.bst
I couldn't open database file Refrences/ref.bib
---line 56 of file thesis.aux
: \bibdata{Refrences/ref
: }
I'm skipping whatever remains of this command
I found no database files---while reading file thesis.aux
Warning--I didn't find a database entry for "liucloud"
(There were 2 error messages)
``````
this is what i have for the bib section:
``````\bibliographystyle{Classes/CUEDbiblio}
\renewcommand{\bibname}{References}
\bibliography{Refrences/ref}
``````
any suggestions? All i want is to be able to use the Bibdesk DB & be able to cite everything...
-
Welcome to TeX.SX! Do you have a file named `ref.bib` in the `Refrences` subdirectory? Maybe it's just a typo: shouldn't it be `References`? – egreg Nov 3 '12 at 15:20 oh yeah :/ now its getting to the original errors i had earlier, bibtex is saying The style file: plain.bst Database file #1: References/ref.bib – Callum Bonnyman Nov 3 '12 at 15:35 If you have `\bibliographystyle{Classes/CUEDbiblio}` I can't see how you can get `The style file: plain.bst`. – egreg Nov 3 '12 at 16:19 ohi changed the style to plain just to try and fix it – Callum Bonnyman Nov 3 '12 at 20:45 And what are the errors you get now? – egreg Nov 3 '12 at 21:37
## closed as too localized by lockstep, Kurt, Thorsten, Stefan Kottwitz♦Nov 17 '12 at 18:20
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, see the FAQ.
|
{}
|
IT Workshop
Document Sample
ITWS Lab Department of Computer Science and Engineering
Department
Of
Computer Science & Engineering
IT Workshop Lab Manual
BALAJI INSTITUTE OF TECHNOLOGY AND
SCIENCE
Department of computer science & engineering
In-charge HOD Principal
Prepared by: Approved & Issued by: w.e.f Date:
Reviewed by:
Balaji Institute of Technology and Science 1
ITWS Lab Department of Computer Science and Engineering
BALAJI INSTITUTE OF TECHNOLOGY AND SCIENCE
Laknepally(V), Narsampet, Warangal
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Lab Manual for the Academic Year 2011-12
(In accordance with JNTU syllabus)
SUBJECT : ITWS LAB
STREAM : CSE
H.O.D
Balaji Institute of Technology and Science 2
ITWS Lab Department of Computer Science and Engineering
INTRODUCTION ............................................................................................................................................................................ 4
PC HARDWARE .............................................................................................................................................................................. 5
INTERNET AND WORLD WIDE WEB ..................................................................................................................................... 43
PRODUCTIVE TOOLS ................................................................................................................................................................. 52
MS PUBLISHER ............................................................................................................................................................................. 52
Inserting and Editing Text Objects .......................................................................................................................................... 52
Create, use, or change a template in Publisher ...................................................................................................................... 55
Layouts .................................................................................................................................................................................... 58
Inserting and Removing Pages ................................................................................................................................................ 59
Publish a Publisher Web site .................................................................................................................................................. 62
LATEX ......................................................................................................................................................................................... 71
What is LaTeX? ....................................................................................................................................................................... 71
Why LaTeX, not MS Word? ..................................................................................................................................................... 71
Where to get LaTeX? ............................................................................................................................................................... 71
LaTeX package structure ........................................................................................................................................................ 72
LaTeX Skeleton........................................................................................................................................................................ 72
How To Run LaTeX ................................................................................................................................................................. 72
Latex Flowchart ...................................................................................................................................................................... 72
The syntax of LaTeX ................................................................................................................................................................ 74
File formats encountered in Latex........................................................................................................................................... 74
MICROSOFT WORD ....................................................................................................................................................................... 77
MICROSOFT EXCEL ................................................................................................................................................................... 87
MICROSOFT POWERPOINT .......................................................................................................................................................... 148
Balaji Institute of Technology and Science 3
ITWS Lab Department of Computer Science and Engineering
INTRODUCTION
The objective of IT Workshop is to impart basic computer usage and maintenance skills and to introduce
you to a suite of productivity tools that will aid in your day to day activities.
IT workshop works in a learning-by-doing mode. It concentrates more on hands-on experience for the
participants rather theoretical classes. It enables the participant to make the best use of Microsoft Office
Suite in their day-to-day requirements and make use of it to improve the standards in the educational
environment. The IT Workshop prepares the participant to have a hands-on experience in maintaining and
troubleshooting a PC by themselves.
Computer Hardware, Windows & Linux
Hardware comprises all of the physical parts of a computer, as distinguished from the data it contains or
operates on. Software provides instructions for the hardware to accomplish tasks.
Windows is a range of closed source proprietary commercial operating environments for personal
computers and also servers. This range was first introduced by Microsoft in 1985 and eventually has come
to dominate the world of personal computer market. All recent versions of Windows are full-fledged
operating systems.
Linux is a computer operating system. It is among the most famous examples of free software and of open-
source development. Initially, Linux was largely developed and used by individual enthusiasts.
Productivity Tools
Microsoft Office is a suite of productivity programs created by Microsoft and developed for Microsoft
Windows and Apple Macintosh operating systems. In addition to the office applications, it includes
associated servers and Web-based services.
Office is considered to be the de facto standard for productivity programs, and has many features not present
in other suites. However, the reverse is also true, with other programs having capabilities that Office doesn't.
Microsoft Office suite includes Word, Power Point, Excel, Publisher, Outlook in most of its versions.
Internet and World Wide Web
Internet & World Wide Web module introduces the different ways of hooking on to the internet from
home and workplace and effectively usage of the internet. Usage of web browsers, email, newsgroups and
discussion forums would be covered.
Balaji Institute of Technology and Science 4
ITWS Lab Department of Computer Science and Engineering
PC Hardware
Identification of the peripherals of a computer, components in a CPU and its functions. Draw the block
diagram of the CPU along with the configuration of each peripheral.
COMPUTER HARDWARE
Introduction to Computer Hardware:
Hardware is the physical appearance of the devices or tools. It is what which we can touch and feel.
Computer Hardware consists of the Monitor, CPU, Keyboard, Mouse and all other devices connected to the
computer either externally or internally.
A typical computer (personal computer, PC) consists of a desktop or tower case (chassis) and the following
parts:
1. CPU The central processing unit contains the heart of any computer, the processor. The processor is
fitted on to a Mother Board. The Mother Board contains various components, which support the
functioning of a PC.
2. System board/Motherboard which holds the Processor, Random Access Memory and other parts,
and has slots for expansion cards
3. RAM (Random Access Memory)- for program execution and short term data-storage, so the
computer doesn't have to take the time to access the hard drive to find something. More RAM can
contibute to a faster PC.
Balaji Institute of Technology and Science 5
ITWS Lab Department of Computer Science and Engineering
4. Buses : PCI bus, PCI-E bus, ISA bus (outdated), USB, AGP
5. Power Supply - a case that holds a transformer, voltage control and fan
6. Storage controllers, of IDE, SCSI or other type, that control hard disk, floppy disk, CD-ROM and
other drives$$;$$the controllers sit directly on the motherboard (on-board) or on expansion cards
7. Video display controller that produces the output for the computer display
8. Computer bus controllers (parallel, serial, USB, Fire wire) to connect the computer to external
peripheral devices such as printers or scanners
9. Some type of a removable media writer:
10. CD - the most common type of removable media, cheap but fragile.
CD-ROM, , CD-RW, CD-R, DVD, DVD-ROM., DVD-RW, DVD-R,
11. Floppy disk
Balaji Institute of Technology and Science 6
ITWS Lab Department of Computer Science and Engineering
12. Tape Drive - mainly for backup and long-term storage
13. Internal storage - keeps data inside the computer for later use.
14. Hard disk - for medium-term storage of data.
15. Disk array controller
16. Sound card - translates signals from the system board into analog voltage levels, and has terminals
to plug in speakers.
17. Networking - to connect the computer to the Internet and/or other computers
18. Modem - for dial-up connections
19. Network card - for DSL/Cable internet, and/or connecting to other computers.
Balaji Institute of Technology and Science 7
ITWS Lab Department of Computer Science and Engineering
20.Other peripherals: In addition, hardware can include external components of a computer system.
The following are either standard or very common.
Input , Keyboard, Pointing devices, Mouse, Trackball, Joystick, Game pad
21.Output : The ouput devices are:
Printer, Speakers, Monitor, Networking, Modem, Network card
Balaji Institute of Technology and Science 8
ITWS Lab Department of Computer Science and Engineering
COMPUTER ASSEMBLING AND TROUBLE SHOOTING
How to Build Your Own PC
For many, building a computer is scarier than working on a car. Saving money isn’t the only benefit to
further down the road. You’ll also get exactly what you want. Before you can sit down at your new
computer desk though, you’ll need to actually build the system. Piecing a computer together may sound like
a tough task, but if you take a couple of precautions, there is nothing to worry about. Most components
include warranties and a toll-free number. If you suspect a particular piece of hardware is causing dissention
in the ranks, don’t hesitate to ask for help.
Before We Begin:
In order to ensure everything goes smoothly, gather a few important tools. A head screwdriver is a must and
needle-nosed pliers are often helpful. Buy quality thermal grease to keep the processor in contact with the
heat sink. If you don’t have an anti-static wrist band, make a conscious effort to touch a ground point every
so often (exposed metal on the case works fine) to keep electrostatic discharge from damaging any of your
components.
Step One: Case Preparation
You need to make sure your case is ready to accept the insides of a computer. After opening the empty case
(usually accomplished by removing two screws on one side), lay the case on its side, so the motherboard can
be dropped into place. If the case includes screws and cables, take those out and set them aside. There
Balaji Institute of Technology and Science 9
ITWS Lab Department of Computer Science and Engineering
should be a set of copper colored spacers in the bag of screws – we’ll use those to mount the motherboard
above the metal plate on the side of the case. You may need to lay your motherboard down in the case to
determine where the copper spacers are needed, but be extra careful – if you add a spacer that doesn’t
correspond to a mounting hole in the motherboard, you risk a short-circuit.
Next, you’ll want to check the thin, metal plate towards the rear of the case that includes holes for the
PS/2, serial, parallel, and USB ports. If it matches the configuration of your motherboard, you’re set.
If not, you’ll need to remove the plate by sliding it out. Again, be careful$$;$$the sides of the plate are
sharp. Once the proper plate is in place, set the case aside for a moment and focus on the
motherboard.
Step Two: Populate the Motherboard
Working on a motherboard that has already been mounted can get tricky, so it is best to install the processor
and memory before the board is installed in a case. Both the Pentium 4 and Athlon XP plug into a processor
socket with no force, so there should be no reason to apply pressure when installing the processor. First, lift
the arm adjacent to the socket. Then align the processor with the socket according to the pattern of pins on
the socket interface. There is only one way the processor will fit, so again, do not apply pressure while
inserting the chip. Finally, close the arm, securing the processor on the motherboard. Now, using the
thermal grease mentioned previously, apply a thin film over the processor’s core.
The process isn’t nearly as graceful for Athlon XP owners. In fact, be forewarned that the processor
core is sensitive to pressure, so if you feel you may be pushing too hard to affix the heat sink, take a
quick break to re-evaluate your strength, tough guy. There is only one way that a Socket A heat sink
should fit, so be sure that the larger end of the socket aligns with the cut-out section of the heat sink.
One end will clip easily onto the motherboard, while the other will require more persuasive coercion.
Balaji Institute of Technology and Science 10
ITWS Lab Department of Computer Science and Engineering
In the following picture, I’ve demonstrated a technique for attaching a heat sink. Use a screwdriver to
push down on the clip while pulling outwards with a set of
pliers.
Step Three: Fixing Memories:
Depending on what type of motherboard you’ve got, there may be some variation in how memory is
installed. Still, there are a few general rules of thumb you’ll want to abide by. First, don’t immerse the
modules in water.
Second, pay close attention to the type of RAM supported by your motherboard. Some boards
support both PC133 and DDR memory, but the majority is constrained to a single standard. If DDR
is your poison of choice, note that the modules will only fit into the 184-pin slots one way. Boards that
support 16-bit RDRAM require that two modules be used at a time. If the board has four slots and
you’ve only got two modules, be sure that the remaining two are terminated with a CRIMM module
(usually included with i850 motherboards). The installation process itself is simple: pull the plastic
clips on each end of the slot, inset the module according to the slot’s keying, and apply equal force to
the entire module until it clicks into place. Repeat, if necessary.
Since the motherboard now houses a processor and memory, it can be installed in the already-been-prepped
case. Line up the mounting holes with the copper spacers and use the included screws to mount the board.
Balaji Institute of Technology and Science 11
ITWS Lab Department of Computer Science and Engineering
Now that your custom machine is taking shape, it may be a good time to step back for a break. Relax,
meditate, take some pictures, watch Friends, or have a Big Blue Banana.
Step Five: Prepare the Cables
Most motherboards include two IDE cables and a floppy drive connector. While the interior of the case is
still clean (thus reasonably accessible), attach the cables to the motherboard. Note that one end of the cable
has two connectors close together – this end attaches to your IDE device of choice, while the other end goes
to the motherboard. Each cable should be marked with a red wire to indicate Pin 1. It is imperative to match
Pin 1 on the cable with Pin 1 on the motherboard and again with Pin 1 on the hard disk drive or CD-ROM.
Conventional IDE cables are fine for the most part, but in the interest of cleanliness, we’ve
developed a soft spot for round cables. Not only do these cables take up less room, but they are also
easier to tuck away, promoting better air flow throughout your case.
Balaji Institute of Technology and Science 12
ITWS Lab Department of Computer Science and Engineering
With the cables out of the way, you can now install your hard disk drive, CD-ROM drive and floppy disk
drive. First, you’ll want to make sure each drive is designated as a ‘master’ or ‘slave’ drive using the
jumpers on the back of each drive. If you’ve got one hard drive and one CD-ROM, you’ll see the best
performance from both devices if each is installed onto its own channel. In that case, both drives can be set
as ‘masters.’ With the addition of a CD-RW drive, you would want to assign one drive as a ‘master’ and one
as a ‘slave,’ leaving the hard drive on its own channel.
Now, you’re ready to add a CD-ROM drive. You may have a metal panel preventing you from inserting the
drive into a 5.25" slot. If so, remove the panel by rocking it back and forth until it comes loose. If your case
uses rails, attach them to the drive and slide it into the chassis. Otherwise, use the included screws to secure
the drive.
The floppy drive can be installed using the same method, only use one of the external 3.5" inch bays.
Attach the appropriate cable and secure the drive using the same small screws.
Finally, install your hard disk drive in an internal 3.5" bay. Many cases sport detachable disk drive
bays that often ease installation, but if we were really looking for the easy way out, we would have
picked up a G4 Cube. Attach the ends of each cable to the corresponding drive. For instance, the end
of the primary IDE cable should run to the hard drive. Similarly, the end of the secondary cable
should go to the secondary ‘master’ drive, while the second connector attaches to the secondary
‘slave.’
Balaji Institute of Technology and Science 13
ITWS Lab Department of Computer Science and Engineering
Step Seven: In Go the Cards
Expansion cards add capabilities beyond what integrated sound and graphics can do. Additionally, you can
buy cards that add SCSI, USB 2.0, Gigabit networking – even cable television support!
Unless your new system is to be used exclusively for business, it’s a safe bet that a new graphics card
will find its way into your AGP slot (the brown one in the middle of the motherboard). Nowadays,
graphics cards are cooled by heat sinks and fans, much like processors. It should come as no surprise,
then, that high-end cards generate lots of heat. When I build a computer, I typically leave the white
PCI slot closest to the video card empty for plenty of air flow. Installing the card itself is a snap –
position the card over the slot and push down gently until it is fully inserted. Use one of the screws
included with the case to secure the card to the chassis. Use the same procedure to install each of your
other cards. If you haven’t yet purchased them, consider an upgraded sound card and network card,
at the least.
>
Step Eight: Connecting the Connectors
In order for your computer to turn on when you hit the power button, you need to connect the switches and
light emitting diodes (LEDs) from your case to the motherboard. The connectors themselves are usually
labeled, but it can be a little harder to locate the pins on the motherboard. Your best source for this data is
the manual included with the board. Once you have the connectors, well, connected, we can move on to the
next step. Don’t worry$$;$$we’ll test the lights and switches a little later.Dont forget refer to the motherboard
manual while connecting the connectors
Step Nine: Power supply
We’ve waited a long time for this – simply, I have no desire to play with hardware actively fed by an
electrical socket. I have no desire to look like Carrot Top, so I never add power until I’m done under the
proverbial hood. We’re pretty much done though, so go ahead and connect the large 4-pin power connectors
to the hard disk drive and CD-ROM drive. The small 4-pin Molex connector is required for the floppy disk
drive. >
If you’ve got a Pentium 4 processor, not only will you need to connect the ATX power connector, but you’ll
Balaji Institute of Technology and Science 14
ITWS Lab Department of Computer Science and Engineering
also require a 4-pin 12V auxiliary connector. Athlon XP-compatible motherboards only need power from
the standard ATX connector. At this point, feel free to connect the case’s power supply to a wall socket.
Step Ten: Check Properly
Before you put the cover back on the case, it would be wise to test the machine. Connect a keyboard and
mouse to the motherboard and a display to the video card. Press the power button and immediately hit the
‘Delete’ key to enter the motherboard’s BIOS. Check the front of the case to ensure both the power and hard
drive lights are functioning (you will probably need disk activity before you can check the hard drive LED).
Eject the CD-ROM tray to check power to the drive. Finally, check the BIOS to make sure the drives are
configured as you originally intended. This, unfortunately, is where we part ways – for tips on configuring
Hopefully you haven’t electrocuted yourself. I think you’d agree
that building a new computer is a learning experience,
regardless if it’s your first time or fiftieth. There is always
something that can go wrong, and if you build new machines for
long enough, anything and everything will happen. If things
don’t go your way the first time, be patient and troubleshoot the
problem. Always remember to keep manuals of all components
with you while fixing your PC.
Balaji Institute of Technology and Science 15
ITWS Lab Department of Computer Science and Engineering
Windows XP Installation:
Windows XP (codename Whistler, also known as Windows NT 5.1) is the latest desktop version of the
Microsoft Windows operating system. It was made publicly available on October 25, 2001. Two editions of
Windows XP are most commonly available: Windows XP Home Edition which is targeted at home users
and Windows XP Professional which has additional features such as dual-processor support and the ability
to join a domain, a grouping of centrally managed Windows computers. The letters "XP" originate from the
word "Experience".
BIOS SETUP & DISK FORMATTING
BIOS SETUP
What IsBIOS? BIOS is an acronym for Basic Input Output System.
Why BIOS?
To run any system, there must be default settings so that the system can load those settings when it is
started or restarted. For a computer system the basic I/O settings and boot process details are necessary to
start a system. All these default, predefined settings will be loaded in the BIOS and whenever we start the
system, these settings will be loaded. How to view BIOS?
Whenever we start the system, we can enter into the BIOS Setup Utility by pressing Del Key.
Sometimes an F1 or F8 key has to be instead of DEL key, depending on the type of BIOS.
When we enter in to this utility we get these following menus/services, depending upon our mother board.
Main
In main Menu, we can view the details such as BIOS Version, Processor Type, and Speed, RAM Size and
the system bus speed and memory speed.
We can change the settings like language system time and date. We can even change the hyper threading
facility if the processor supports this technology.
We must be very careful when we change these settings otherwise it may cause our system to malfunction.
Here, we can change the settings of PCI devices, Floppy Drives configuration and chipset, USB peripheral
devices and even monitoring the Hardware.
Security:
Balaji Institute of Technology and Science 16
ITWS Lab Department of Computer Science and Engineering
We can set the supervisor password, to restrict unauthorized users to enter the BIOS setup utility.
User password can also be set to restrict the unauthorized persons to boot or use the system.
We can even set the Chassis Intrusion to protect the system devices from removing the components of the
system.
Power:
The power settings protect the system from power failures by configuring the ACPI.
For example, after power failure we can stay off the system or Power on the system or else we can even
make the system to restore its previous state by selecting the appropriate options.
Boot:
DISK FORMATTING:
What is Disk Formatting?
Disk formatting is nothing but creating new tracks and sectors on a magnetic storage device.
Why Disk Formatting?
Every disk must be formatted before the first usage. Because then only we can address each and every
memory unit.
How to Disk Format?
To format the disks we have the following methods.
Fdisk
FDisk is a windows command, throw which we can create partitions on a hard drive so that we can format
each drive and use the same.
Balaji Institute of Technology and Science 17
ITWS Lab Department of Computer Science and Engineering
Format
Format is an external command which will create the actual tracks and sectors on a magnetic drive.
To format a partition we need to use format command.
Disk Manager
Disk Manager is a tool to manage a magnetic drive, through which we can create the partitions as well as
formatting the particular partitions at a time.
Partition Magic
Balaji Institute of Technology and Science 18
ITWS Lab Department of Computer Science and Engineering
Partition Magic is also a tool to do the same thing but it gives its services available in GUI which is more
user friendly.
Red Hat Linux Installation Process:
1. LINUX BOOT OPTIONS
Actually Linux can be installed in two different modes, based on the requirement of the user.
Graphical Mode.
Text Mode.
Graphical Mode - In this you can work with Graphical Interface (i.e., it supports mouse and Icons ). By
clicking the icon with the mouse, you can perform related action.
To install Linux in Graphical Mode Press Enter.
Text Mode - In this mode you have to interact with character based interface ( i.e., Command prompt ).
To install Linux in Text Mode Type : Linux text and Press Enter.
After selecting the mode of installation, it goes on detecting the basic input output devices and file systems.
And at last it displays a screen asking whether to test the CD inserted to install or to Skip the test process.
Otherwise we can test total installation CD’s.
On completion of testing the CD’s, it goes on loading an installation program “ANACONDA” which helps
us in the installation of the remaining part.
2 WELCOME TO INSTALLATION PROCESS
It starts with the display of the welcome screen containing the online help , and four buttons to help
us in the different activities in the installation process.
Hide Help/Show Help - Which helps you in guiding the installation process, which can be activated
or hidden.
Release Notes - Which contain the Basic Hardware Requirements that are necessary for the installation of
the Red Linux 9.0 and some other post-installation issues.
Next - This button allows you to go to next step of the installation process by the current step.
Back - This button allows you to move back of the installation process to make any changes that previously
mentioned.
Action: click “Next” to move to next screen.
3. SELECTING A LANGUAGE
Balaji Institute of Technology and Science 19
ITWS Lab Department of Computer Science and Engineering
It displays a screen containing various languages, to select a language you would like to use during this
installation process.
4. CONFIGURING KEYBOARD AND MOUSE
Here we need to select our own keyboard and mouse layouts which will help you to interactively proceed in
the installation process.
At this point of time it displays you the different types of keyboard layouts. So that you can select your
desired one that you would like to use for the system.
And also choose the appropriate Mouse for the system, based on the following:
Do you have a PS/2, USB, Bus or Serial mouse?
Hint:- If the connector your mouse plugs into is Round - It is a PS/2
If the connector your mouse plugs into is Rectangular - It is a USB mouse
If the connector your mouse plugs into is Trapezoidal - It is a Serial mouse
Select the exact mouse type among the available.
5. TYPE OF INSTALLATION:
There are different installation types that are available which will enable you to select that will best meet
There are four different types of installations are there –
Personal Desktop
- You select it for personal computers or laptops, select this installation type to install a graphical desktop
environment and create a system ideal for home or desktop use.
Work Station
- This option installs a graphical desktop environment with tools for software development and system
Server
- If you would like to set up file sharing, print sharing, and web services and additional services.
Custom
- Select this installation type to gain complete control over the installation process,
Including software package selection and authentication preferences.:
6. PARTITIONING THE DISK
Partitioning the disk can be done either automatically or manually.
AUTOMATIC PARTITIONING
– By selecting automatic portioning, you will not have to use partitioning tools to assign mount points,
create partitions, or allocate space for your installation. Automatic partitioning allows you to have some
control concerning what data is removed from your system.
To remove only Linux partitions remove all Linux partitions on this system.
Balaji Institute of Technology and Science 20
ITWS Lab Department of Computer Science and Engineering
To remove all partitions on your hard drive, select remove all partitions on this system.
To retain your current data and partitions, assuming you have enough free space available on your
hard disk, select Keep all partitions and use existing free space.
You can review the partitions that are automatically created using the check box Review (and modify if
needed) the partitions created.
MANUAL PARTITIONING
– To partition manually, choose the Disk Druid partitioning Tool. For the manual partitioning of Linux
installation you need assign disk space for the three compulsory file systems, they are /boot, /(root), swap
/boot
- This type of partition should of ext3 file system type. For this /boot partition a minimum of about 150MB
is necessary.
Swap
The swap partition should of swap file system type having a minimum of the double the RAM available on
(i.e., if, RAM is of 512MB, your swap should be a minimum of 1024MB.)
/(root) –
The symbol ‘/’ stands for the root. This root partition should be a minimum of 5GB. And you can also
To add a new partition Just click on the NEW button and select your mount point (i.e., directory of partition
ex: /, /boot, /user, etc., ), select your file system type among the available i.e. Ext3, ext2, swap, vfat, etc., ),
and you have different additional size options like Fixed Size, Fill all space up to(MB), Fill to maximum
allowable size. And also you can make a partition to be primary partition and check for the bad blocks on
each partition.
The GRUB boot loader will allow you to boot other operating systems. It will allow you to select an
operating system to boot from the list. To add another operating system. You can also add other operating
systems that are not detected automatically.
For greater system security, you can set your password for the boot loader. To avoid unauthorized changes
to the system.
You can also change the type of boot loader other than GRUB, among the available like LILO. And also
you can avoid to install boot loader.
8. NETWORK CONFIGURATION
With this option you can set your Network devices manually or using DHCP (Dynamic Host Configuration
9. FIREWALL CONFIGURATION
A firewall configuration is set between yours computer and network. And decides which resources of your
computer are accessible by the remote users on the network. On proper configuration of firewall we can set
different security levels for the system.
Balaji Institute of Technology and Science 21
ITWS Lab Department of Computer Science and Engineering
By using firewalls we can avoid any entrusted passage of data and also we can set our own protocol
supports.
This screen shows different additional languages for installation. These additional languages can be used to
switch after installation process.
11. SELECTING A TIME ZONE
To set our time zone we can do it either by selecting computers physical location or by your time zone’s
offset from Universal Time, Coordinated. This screen shows two tabs namely location and UTC Offset.
First tab offers you the ability to configure by location. Second tab allows to set UTC Offset.
13. PERSONAL DESKTOP DEFAULTS
With this screen we can accept the default package list or we can customize the set of packages to be
installed.
14. SELECTION OF PACKAGES TO INSTALL
On selecting the customized set of packages we can select our own selection of desktops, applications,
servers, development tools and system tools to be installed among the available.
And also we have an option to select a minimal set of packages and all the packages that are available which
will install complete set of packages(about 1400) which will require about 4850 MB of space.
This is the final step to make any modifications to the installation process. Once you click the next button
you cannot do any modifications.
16. INSTALLING THE PACKAGES
First it formats the file systems and copies the files to our hard disk to continue installation. Then there starts
the installing of packages which may take up to several minutes of time during which we need to insert next
two CD ROMs to complete the installation process.
17. CREATING A BOOT DISK
Here the prompts you to create a Linux boot disk on your choice for your further requirement.
At this stage you need to select your video card type and monitor configuration and also you restore to the
original values.
19. END OF INSTALLATION PROCESS At the end of the installation process it will remove all the media
that is used by the installation. And reboots your system again.
Screenshots
Balaji Institute of Technology and Science 22
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 23
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 24
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 25
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 26
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 27
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 28
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 29
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 30
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 31
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 32
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 33
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 34
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 35
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 36
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 37
ITWS Lab Department of Computer Science and Engineering
Linux Bash Commands:
Basic Commands:
Before we start, here are some ground rules. Anything that is red means to type it, if you see brackets
<option> it means you will have to make a decision (an option). Don't type the brackets < > for the option!
Look for italic words for they will give a clue of what commands I'm talking about.
The first time you login to Linux you will have to login as root
Then it will ask you for a password, and again to verify. Now you are in the root account.
What's the root account? Root is where the user has full access to everything on the system. Normally, the
root account is only used when performing system administration tasks which includes shutting down.
d="4.2">
Balaji Institute of Technology and Science 38
ITWS Lab Department of Computer Science and Engineering
Exiting, restart, and shutdown
How to shut down
the Linux OS? Type the command
#shutdown -h now
If you which to restart the Linux OS then type
#reboot
If you want to get out of the root account then type
#exit
Balaji Institute of Technology and Science 39
ITWS Lab Department of Computer Science and Engineering
Hardware Troubleshooting:
Basic troubleshooting:
Sometimes things do not work exactly as planned at this point. Sometimes the system will not power on at
all. Sometimes it will power on, but you get no video. Sometimes you will get beep codes. Sometimes you
hear the fans, but the rest of the PC just sits there and does nothing. If things didn't go according to plan,
troubleshoot the system. Walk mentally through the boot process and check all hardware as it goes. Think
like the computer thinks, if you know what I mean. Here is a list of some of the more common problems.
1. The power does not even turn on. This sometimes happens on ATX machines and it usually tracks
down to the fact that the power switch is not properly connected to the motherboard or it is not
connected at all. Find the power switch lead and make sure it is connected to the motherboard, as
described in Step 11. It’s a possibility that simply reversing the lead will do the trick. If this is the
not the case, then make sure the motherboard is not grounded somehow. Make sure that the board is
not touching the case (this is what the spacers are for). Make sure that none of the screws that hold
the board in place is touching anything metal or any of the electrical pathways on the motherboard.
If you have any doubt on this, you can remove each screw one at a time and place a washer on them.
You do not need to remove the motherboard to do this.
2. The PC boots, but it is giving beep codes. This is actually better than having to track everything
down on your own, because at least the PC is giving you a hint as to what is wrong. You can also use
the PC Mechanic Beep Codes E-book available on the PC Mechanic CD to track it down for other
BIOS versions. Often, these beep codes will not tell you exactly what the problem is, but will point
you at the trouble device. This information will then get you pointed in the correct direction.
3. The fans come on, but you get no video or beeps. Sometimes, this is because some key component
may not be plugged in well or may not be operational. Check the memory modules and the processor
to be sure they are firmly installed. You might want to make sure the processor is actually working.
One way that I have used to see if a processor is working is to remove or unplug the CPU fan and
place your fingers on the CPU to see if it heats up real fast. If it does, its OK and don’t let it run this
way for long. If it remains at room temperature for awhile, then there is no juice going through the
processor and it may need replacing. The keyboard doesn’t seem to work. This one doesn’t happen
too often, but if it does, your two trouble sources will be the keyboard itself or the keyboard
controller on the motherboard. Hope it isn’t the second one.
Balaji Institute of Technology and Science 40
ITWS Lab Department of Computer Science and Engineering
Software Troubleshooting:
BIOS SETUP & DISK FORMATTING
BIOS SETUP
What Is BIOS?
BIOS is an acronym for Basic Input Output System.
Why BIOS?
To run any system, there must be default settings so that the system can load those settings when it is started
or restarted. For a computer system the basic I/O settings and boot process details are necessary to start a
system.
All these default, predefined settings will be loaded in the BIOS and whenever we start the system, these
How to view BIOS?
Whenever we start the system, we can enter into the BIOS Setup Utility by pressing Del Key. Sometimes an
F1 or F8 key has to be instead of DEL key, depending on the type of BIOS.
When we enter in to this utility we get these following menus/services, depending upon our mother board.
In main Menu, we can view the details such as BIOS Version, Processor Type, and Speed, RAM Size and
the system bus speed and memory speed.
We can change the settings like language system time and date. We can even change the hyper threading
facility if the processor supports this technology.
We must be very careful when we change these settings otherwise it may cause our system to malfunction.
Here, we can change the settings of PCI devices, Floppy Drives configuration and chipset, USB peripheral
devices and even monitoring the Hardware.
Security
We can set the supervisor password, to restrict unauthorized users to enter the BIOS setup utility.
User password can also be set to restrict the unauthorized persons to boot or use the system.
Balaji Institute of Technology and Science 41
ITWS Lab Department of Computer Science and Engineering
We can even set the Chassis Intrusion to protect the system devices from removing the components of the
system.
Power
The power settings protect the system from power failures by configuring the ACPI.
For example, after power failure we can stay off the system or Power on the system or else we can even
make the system to restore its previous state by selecting the appropriate options.
Boot
Silent boot : If this option is enabled it displays only the OEM logo and in the background POST(Power on
Self Test) completes. If this is disabled, instead of LOGO, we can view POST messages
Rapid BIOS Boot: By enabling this option it will decrease the time needed to boot the by skipping some
unnecessary tests.
Here, we can also set the boot sequence from the available devices by selecting Boot Device Priority.
We can even view the Hard Drives and any removable devices and attached to the system.
Exit
By selecting the appropriate options we can exit from the BIOS setup like exiting the setup by saving or
Balaji Institute of Technology and Science 42
ITWS Lab Department of Computer Science and Engineering
Internet and World Wide Web
Orientation and Connectivity Boot Camp:
To configure TCP/IP settings
1. Open Network Connections.
2. Click the connection you want to configure, and then, under Network Tasks, click Change settings
of this connection.
3. Do one of the following:
o If the connection is a local area connection, on the General tab, under This connection uses
the following items, click Internet Protocol (TCP/IP), and then click Properties.
o If this is a dial-up, VPN, or incoming connection, click the Networking tab. In This
connection uses the following items, click Internet Protocol (TCP/IP), and then click
Properties.
4. Do one of the following:
o If you want IP settings to be assigned automatically, click Obtain an IP address
automatically, and then click OK.
o If you want to specify an IP address or a DNS server address, do the following:
Click Use the following DNS server addresses, and in Preferred DNS server and
Alternate DNS server, type the addresses of the primary and secondary DNS
servers.
5. To configure DNS, WINS, and IP Settings, click Advanced.
Notes
To open Network Connections, click Start, point to Settings, click Control Panel, and then double-
click Network Connections.
You should use automated IP settings (DHCP) whenever possible, for the following reasons:
o DHCP is enabled by default.
o If your location changes, you do not have to modify your IP settings.
o Automated IP settings are used for all connections, and they eliminate the need to configure
settings such as DNS, WINS, and so on.
To make a local area connection
If you have a network adapter installed, and have set up a home or small office network, you are
connected to a local area network (LAN). You are also connected to a LAN if your Windows XP
Professional computer is part of a corporate network. When you start your computer, your network
Balaji Institute of Technology and Science 43
ITWS Lab Department of Computer Science and Engineering
adapter is detected and the local area connection automatically starts. Unlike other types of
connections, the local area connection is created automatically, and you do not have to click the local
area connection in order to start it.
To make an Internet connection
1. Open Network Connections.
2. Under Network Tasks, click Create a new connection, and then click Next.
3. Click Connect to the Internet, and then click Next.
4. Choose one of the following:
o If you already have an account with an Internet service provider (ISP), click Set up my
connection manually and then click Next.
o If you have a CD from an ISP, click Use the CD I got from an ISP and then click Next.
o If you do not have an Internet account, click Choose from a list of Internet service
providers (ISPs) and then click Next.
5. From your choice above, click one of the following:
Set up my connection manually
o If you are connecting to your ISP using a standard 28.8 Kbps, 56 Kbps, or ISDN modem,
click Connect using a dial-up modem, click Next, and follow the instructions in the wizard.
o If your DSL or cable modem ISP connection requires a user name and password, click
Connect using a broadband connection that requires a user name and password, click
Next, and then follow the instructions in the wizard.
o If your DSL or cable modem ISP connection is always on and does not require you to type a
user name and password, click Connect using a broadband connection that is always on,
click Next, and then click Finish.
Use the CD I got from an ISP
o Click Next, and then click Finish. Insert the CD provided by your ISP and follow the
instructions.
Choose from a list of Internet service providers (ISPs)
o To create an Internet account using MSN Explorer, click Get online with MSN, and then
click Finish. Follow the instructions in MSN Explorer.
o To choose an ISP, click Select from a list of ISPs, click Finish, and then double-click Refer
me to more Internet service providers. Follow the instructions in the wizard.
Balaji Institute of Technology and Science 44
ITWS Lab Department of Computer Science and Engineering
Web Browsers and Surfing the Web:
•The internet is a network of computer networks worldwide•The web is a tool used to retrieve information
published on the internet•To navigate the web we use a browser I.E. Internet Explorer, Mozilla Fire Fox
…etc
•Each computer on the internet has its own address
•E-mail addresses discussed in e-mail classes
•Each document, essay, image, etc. On the WWW has its own address
•Highlighted words or text in a WWW document
•Moves you to a place within same document, or to a web page elsewhere
•An electronic document stored on a web server
•Uses HTML (Hypertext Markup Language)
•May include text, sound, animation, images
•Usually has links to other Web pages or different parts of the same Web site
•Example: http://www.yahoo.com
Customizing the Web Browser
•LAN Proxy Settings
•Bookmarks
•Search Toolbars
•Pop-up blockers
•Managing Plug-ins
Proxy Server
•A server that sits between a client application, such as a Web browser, and a real server.
•It intercepts all requests to the real server to see if it can fulfill the requests itself. If not, it forwards the
request to the real server.
Specifying Proxy Settings in Internet Explorer
•Goto Tools->Internet Options in main menu
•Click on the Connections tab
•Click on Lan Settings button
•Specify the proxy server address and port in the Proxy server section
•If you want to specify different proxies for different servers or you do not want to use proxy servers for
–You can provide different proxy address and ports for different servers
–You can enter addresses for which you do not want to use proxy servers
Navigating the Web Using
Internet Explorer
•Moving within a page;
Balaji Institute of Technology and Science 45
ITWS Lab Department of Computer Science and Engineering
– Page up/down keys
– Up/down arrow keys
– Scroll bar on the right side
–Clicking on hypertext links (may be text, images, URL)
Internet Explorer Toolbar Buttons
Previ St Favorit Ema
ous Previ op Refre es Histoil Websit Go to
Page ous sh On/Offry Pag Print e URL the
Homep
Page
age On/Oe Page reques
ff ted
Websit
e
–Go to the page that you want to add to your Favorites list.
–Type a new name for the page if you want to.
•To open one of your favorite pages, on the Favorites menu, click the page you want to open.
•As your list of favorite pages grows, you can organize them by moving them into subfolders
•Configure Your Browser to access the Internet
•Customize the browser
–Security Settings
–Privacy Settings
–Pop-up Blocking
–Search Toolbar
•Manage Bookmarks
Balaji Institute of Technology and Science 46
ITWS Lab Department of Computer Science and Engineering
Search Engines and Netiquette:
Search Engines
•Software that lets a user specify search terms. The search engine then finds sites that contain those terms.
•Over time a search engine builds a database of searchable terms that can be matched to web sites.
•Examples:
Query
•Terms entered into a form of a search engine’s web page.
•Not necessarily phrased as a question since words such as “what”, “a”, “is” etc. would be ignored.
•Enter specific keywords.
•Make sure your spelling is correct.
Methods of searching
•Use more than one word.
•Use quotes
•Use boolean queries
•Use + sign or - sign
•Use * (wild card)
Boolean Query
AND, OR, NOT
•A AND B–results in sites containing both A and B
•A OR B
–results in sites containing A or B, or both A and B
•A AND NOT B
–results in sites containing A and excludes sites containing both A and B.
Stemming
Some search engines will return results that include variations on the endings of words.
•computer
•computers
•computed
Using boolean queries
•shelf AND ice
–results in URLs of pages containing the word “shelf” and the word “ice” (in any order).
•shelf OR ice
–Results in URLs of pages containing the words “shelf” and ”ice”, or just the word “shelf” or just the word
“ice”.
•computers NOT notebook
–Results in URLs of pages containing the word “computers” but not containing the word “notebook”.
Metasearch Engines
•Performs a search by using more than one search engine to do the search.
Balaji Institute of Technology and Science 47
ITWS Lab Department of Computer Science and Engineering
–www.metasearch.com
–www.metacrawler.com
–www.dogpile.com
–www.infind.com
White Pages
•Used for finding individuals
–www.bigfoot.com
–www.four11.com
–www.whowhere.com
•Mailto Hyperlink – launches a mailer
To open a web page in a new browser window.
•Right-mouse click on the link of interest and then select “Open in new window”.
•Click on the original browser window on the task bar below in order to continue viewing the original web
page while that page loads.•This speeds up your search since you can view one page while another is
•Write search engines to find the following
–To find pages related to Computer Science or Computer Programming
–Who invented Laser
–To find information about AND & OR gates
–To find information about apple(the fruit, NOT Apple computers)
–To search for word School of IT in jntu.ac.in
Netiquette
"Netiquette" is network etiquette, the do's and don'ts of online communication. Netiquette covers both
common courtesy online and the informal "rules of the road" of cyberspace.
What is Netiquette?
Simply stated, it's network etiquette --
that is, the etiquette of cyberspace.
“Etiquette” means “the forms required by good breeding or
prescribed by authority to be required in social or official life.”
In other words, Netiquette is a set of rules for
behaving properly online.
The golden rule: Do unto others as you'd have others do unto you. Imagine how you'd feel if you were in the
other person's shoes. Stand up for yourself, but try not to hurt people's feelings.
Electronic communication lacks the facial expression, gestures and tone of voice to convey your meaning.
It’s easy to misinterpret meaning of words.
Would you say it to the person's face?
If the answer is no, rewrite and reread. Repeat the process till you feel sure that you'd feel as comfortable
saying these words to the live person as you do sending them through cyberspace.
Balaji Institute of Technology and Science 48
ITWS Lab Department of Computer Science and Engineering
Remember, when you communicate through cyberspace your words are written. Chances are they're stored
somewhere. They can come back and haunt you. You don't have to be engaged in criminal activity to want
to be careful. Any message you send could be saved or forwarded by its recipient. You have no control over
where it goes. Standards of behavior may be different in some areas of cyberspace, but they are not lower
than in real life.
Be ethical.
If you encounter an ethical dilemma in cyberspace, consult the code you follow in real life.
If you use shareware, pay for it.
Paying for shareware encourages more people to write shareware. The few dollars probably won't mean
much to you, but they benefit all of cyberspace in the long run.
Breaking the law is bad Netiquette.
If you're tempted to do something that's illegal, chances are it's also bad Netiquette.
Netiquette varies from domain to domain. What's perfectly acceptable in one area may be dreadfully rude in
another.
Netiquette is different in different places, so it's important to know where you are.
Lurk before you leap
When you enter a domain of cyberspace that's new to you, take a look around. Spend a while listening to the
chat or reading the archives. Get a sense of how the people who are already there act. Then go ahead and
participate.
Bandwidth is the information-carrying capacity of the wires and channels that connect everyone in
cyberspace. It also refers to the storage capacity of a host system.
If you accidentally post the same note to the same newsgroup five times, you are wasting both time (of the
people who check each copy) and bandwidth (by sending repetitive information over the wires and requiring
it to be stored somewhere).
You are not the center of cyberspace. Don’t expect instant responses to all your questions, and don't assume
Ensure your message is worth the time it takes to open it.
they really need to know. If the answer is no, don't waste their time. If the answer is maybe, think twice
before you hit the send key.
Take advantage of your anonymity. You won't be judged by color, weight, age or dress sense. You will,
however, be judged by the quality of your writing. So spelling and grammar do count.
Know what you're talking about and make sense. Pay attention to the content of your writing. Ensure your
notes are clear and logical.
Be pleasant and polite. Avoid offensive language, and don't be confrontational for the sake of confrontation.
If you must swear, think up creative alternatives
The strength of cyberspace is in its numbers. The Internet itself was founded and grew because academics
wanted to share information. Don't be afraid to share what you know.
If you ask a question and anticipate a lot of answers, it’s customary to request replies by email instead of to
the group. Share the results of your questions with others, so everyone benefits from the experts who took
the time to write to you.
If you’re an expert, or you've researched a topic that you think would be of interest to others, write it up and
post it. Sharing your knowledge is fun. And it makes the world a better place
opinion without holding back any emotion.
Netiquette does not forbid flaming. Flaming is a long-standing network tradition (and Netiquette never
Netiquette does forbid the perpetuation of flame wars that can dominate the tone and destroy the
Balaji Institute of Technology and Science 49
ITWS Lab Department of Computer Science and Engineering
While flame wars can initially be amusing, they’re an unfair monopolization of bandwidth.
Some people in cyberspace have more power than others. There are wizards in MUDs (multi-user
dungeons), experts in every office, and system administrators in every system.
Cyber hygiene:
Types of Internet Threats
•Viruses
•Network Worms
•Trojans
•Other Malware
•Other Threats
Viruses
•Main purpose is to spread and infect files
•Attach to a file and replicate when file is executed
•More than 100 000 known viruses exists in the world today
•Several hundred new viruses are discovered every month
Network Worms
•Self-replicating Viruses that reside in the active memory of a computer.
•Worms Send themselves out to the Internet from infected systems.
•Either include tiny e-mail server or search for unprotected shared network drives to unload.
Trojan Programs
•Programs that installs themselves stealthly via Internet & provide access for malicious use
•Threats enabled by (/through) Trojans
–DDos attacks
–Data stealing
–Distributed spam eMails
•Do not replicate
•Tracking Cookies – Gathers info of web usage
•Trickles – Reinstalls spyware when deleted
•Keyloggers – Records anything you type!
•Data-Mining
•List goes on...
Other Threats
•Phishing
–Confidential information stealing by fraud emails & web sites (author falsified)
–Several millions of Phishing messages have been sent world wide
–Fastest growing threat today
Balaji Institute of Technology and Science 50
ITWS Lab Department of Computer Science and Engineering
•SPIM
–Instant Messaging SPAM
–Estimated: 4 billion SPIM's during 2004
Diagnosing Infections
•Slow computer, system reboots
•Mouse moves by itself
•Browser goes to unexpected web sites
•Slow internet access
•New desktop toolbars
Diagnosing Infections
•Disabled antivirus scanner or firewall
•Check startup program group regularly for software you didn’t install
•Check Add/Remove programs for software you didn’t install (make a list of installed items on a new
machine and check the list regularly)
Diagnosing Infections
•Check running services monthly
•Check running processes in Task Manager
•Monitor open ports
•Monitor outgoing and incoming connections
Updating
•Few pieces of software are perfect. Many have security flaws that can allow an intruder to take over your
system.
•When the flaws are discovered, the vendor generally fixes them and places patches on their Web sites.–
https://www.Microsoft.com/Security (Windows, Internet Explorer, Outlook, etc.)
–http://www/redhat.com/solutions/security/ (Red Hat Linux)
–http://securityresponse.symantec.com/ (Norton Anti-Virus)
•Some vendors provide a tools for Automatic Updates
Anti-Virus Software
•Examples
–Norton Anti-Virus
–Mc Afee Anti-Virus
–AVG Anti-Virus
AntiSpyware Tools
•Only Software tools exist at the moment
•Programs are trying to detect distinctive signs that spyware places on system
•Popular software
–Spybot: Search & Destroy
Firewalls
•Monitor network traffic and Block access by configured rules
•Software Vs. Hardware
•Stateful inspection
–Examine the headers & content of each passing network packet
Balaji Institute of Technology and Science 51
ITWS Lab Department of Computer Science and Engineering
Productive Tools
MS Publisher
MS Publisher:
Microsoft Publisher helps us to create, customize, and publish materials such as newsletters, brochures,
flyers, catalogs, and Web sites. In this module, we will learn create and publish web pages using MS
Publisher.
Inserting and Editing Text Objects
Many of the concepts and techniques that you know from working with a word processor will carry over to
Publisher. One important thing to remember is that all text needs to be in a text box.
Creating a Text Box
Selecting Text
Editing Text
Changing Type Specifications
Cutting, Copying, and Pasting Text
Creating a Text Box
A text box is an area that contains text only and can be moved to any part of the publication. Type within a
text box can fill only the area of the text box, not the entire publication. Before typing text, a text box must
be created.
1. From the Objects toolbar, select the Text Box
If the Objects toolbar is not visible, from the View menu, select Toolbars » Objects
2. Move the tool across the screen
The cursor looks like a cross.
3. Place the cursor where the text box should begin
4. To create the text box, click and drag
5. Release the mouse button
A text box with a cursor appears.
Balaji Institute of Technology and Science 52
ITWS Lab Department of Computer Science and Engineering
Typing large volumes of text in Publisher is not advised. But using Publisher to type headlines, titles,
captions, headers and footers (type which is usually set off with a different style or placement) is easy.
If you need to type or edit a large amount of text, you may want to use Word.
1. Create a text box
2. Type the text
HINT: To see the text better, zoom in by pressing [F9]. To zoom out, press [F9] again.
Text files from Publisher-compatible word processing programs such as Microsoft Word can be placed into
a Publisher document. Text with little or no formatting generally works best. After placing the text into
Publisher you can edit, format and manipulate it using the same methods as you would for text typed
directly into Publisher.
Pasting text into Publisher that has been copied from another file can be done using the Paste Special
feature. There are various ways that your text can be pasted. Your options when using Paste Special are as
follows:
Option Description
Microsoft Office Word Inserts the copied text from Word and gives you the ability to edit it
Document Object from Publisher using Word.
Unformatted Text Inserts the copied text, removing any existing formatting.
New Table Inserts the copied text as a new Publisher table.
New Text Box Inserts the copied text as a new Publisher text box.
Picture Inserts the copied text as a new Publisher picture frame. You can
select whether you want to use a Windows Metafile or an Enhanced
Windows Metafile.
NOTE: This text can not be edited.
Formatted Text Inserts the copied text, preserving existing formatting.
HTML Inserts the copied text as HTML.
When you paste text, Publisher will create the text boxes necessary to accommodate it or will allow you to
create the text boxes. These two options are described here:
Option Description
Balaji Institute of Technology and Science 53
ITWS Lab Department of Computer Science and Engineering
Autoflow allows you to place text and have Publisher create the text boxes as needed.
Autoflow Text will flow automatically into each text box on the page and onto subsequent pages
Manual text flow requires you to create the text boxes and add the pages necessary to
Manual
accommodate the text you are placing. If you choose to use the manual text flow
Flow
option, be sure to have the Connecting Frames toolbar displayed.
To add text using Paste Special:
1. Select the text to be copied
2. Copy the selected text
3. In Publisher, from the Edit menu, select Paste Special...
The Paste Special dialog box appears.
4. In the As scroll box, select an option
HINT: For text that you will want to edit or format, select New Text Frame.
5. Click OK
The text is now pasted.
Adding Text: Inserting a Text File
1. Create a text box
2. From the Insert menu, select Text File...
The Insert Text dialog box appears.
3. Locate and select the desired file
4. Click OK
If the text file is larger than the text box, a confirmation dialog box appears asking you to choose
between auto or manual flow.
Selecting Text
You will select text when you want to change its type specifications, cut or copy it, or delete it. Use the
Select Objects tool to select text for editing.
HINT: If you have problems selecting the first character at the edge of a text block, start with the last
character and drag to the first character.
Balaji Institute of Technology and Science 54
ITWS Lab Department of Computer Science and Engineering
Editing Text
If you make a mistake while typing, you can always go back and fix it. Editing text in Publisher is much like
editing text in a word processor. You have the following options when editing text:
To insert text, simply type and text will appear at the insertion point
To delete the selected text, press [Delete]
To delete text to the right of the insertion point, press the [Delete] key
To replace the selected text, begin typing.
The selected text will be replaced by the new text that you type.
To change type style, select the appropriate options from the Formatting toolbar.
To move or duplicate the text, from the Edit menu, select Cut, Copy, or Paste.
Create, use, or change a template in Publisher
If you run a typical business, you probably create certain publications — such as newsletters, flyers,
postcards, and gift certificates — over and over again. While each new version is unique, some elements
In a monthly newsletter, for example, much of the layout stays the same, but the content of the newsletter
changes for each version.
You can make a template from any publication by saving that publication as a Publisher template file. Any
template that you save to the default template location becomes available in the New Publication task pane.
When you start a new publication by selecting a template, a copy of the template file opens so that the
original template isn't altered by mistake. If you want to make changes to the template itself, you can open a
Balaji Institute of Technology and Science 55
ITWS Lab Department of Computer Science and Engineering
copy of the template file, make the changes that you want, and then save it again as a template. You can also
create categories for your templates in order to organize them in the New Publication task pane.
You can save time by designing a master publication that reflects your company brand and identity and then
saving it as a template. Then, each time you want to create a new version, you can use the template and add
only the information that is unique to that version. Using a template for a publication that you regularly
produce not only saves time but also ensures quality and consistency.
There are many ways to create a publication in Publisher. Publisher offers many designs that are like
templates, but with dynamic features that make it easy to change the design, layout, colors, and other
elements. You can:
Use a Publisher Master Design Set to promote a consistent company identity.
Use one of the publication wizards to create exactly the type of publication you want, such as a
You can even design a publication by using a design set or publication wizard and then save it as a template.
Save a publication as a template
You can make a template from any publication by saving that publication as a Publisher template file. You
can also download a template from Microsoft Office Online, make any changes that you want, and save the
file as a template that you can use again.
1. Create or open the publication that you want to use as a template.
2. On the File menu, click Save As.
3. In the Save as type box, click Publisher Template.
The destination folder changes to the default template location (C:\Documents and Settings\user
name\Application Data\Microsoft\Templates, if you haven't changed the location in Microsoft Word).
You need to save your template in this folder if you want it to appear on the right side of the New
4. In the File name box, type a name for the template.
5. Click Save.
Use a template to create a publication
This procedure works only if you already created a publication template in Publisher (by choosing
Publisher Template in the Save as type list when you saved the publication) and saved it to the default
template location.
Balaji Institute of Technology and Science 56
ITWS Lab Department of Computer Science and Engineering
Note If you save a publication template to a location other than the default template location, it is not
available in the New Publication task pane, and you cannot use it as a template.
1. On the File menu, click New.
2. In the New Publication task pane, under New from a design, click Templates, and then click the
template that you want to use.
3. Add the content that you want, and make any changes that you want in the new version of your
publication.
4. When you want to save this version of the publication, click Save As on the File menu.
5. Save the publication as a regular Publisher file in any location that you want.
Change a template
This procedure works only if you already created a publication template in Publisher and saved it to the
default template location.
Note If you save a publication template to a location other than the default template location, it is not
available in the New Publication task pane, and you cannot use it as a template.
1. On the File menu, click New.
2. In the New Publication task pane, under New from a design, click Templates.
3. In the Preview Gallery, click the template that you want to change.
4. Make the changes that you want.
5. On the File menu, click Save.
6. In the Save as type box, click Publisher Template.
7. Click the name of the template that you changed.
8. Click Save.
9. When you are asked if you want to replace the existing file, click Yes.
Organize your templates by using categories
By default, templates that you save to the default templates folder appear in the My Templates category
under Templates in the New Publication task pane.
Category property for the template file.
Balaji Institute of Technology and Science 57
ITWS Lab Department of Computer Science and Engineering
1. On the File menu, click New.
2. In the New Publication task pane, under New from a design, click Templates, and then click the
template that you want to categorize.
3. On the File menu, click Properties, and then click the Summary tab.
4. In the Category box, type the name of the category that you want to create.
5. Click OK.
6. On the File menu, click Save.
7. In the Save as type box, click Publisher Template.
8. Click the name of the template that you categorized.
9. When you are asked if you want to replace the existing file, click Yes.
Layouts
Layout guides allow you to create a grid of horizontal and/or vertical lines automatically instead of
Layout Guides...The Layout Guides dialog box appears.
Balaji Institute of Technology and Science 58
ITWS Lab Department of Computer Science and Engineering
1. Select the Grid Guides tab
2. Under the Column Guides section, in the Columns text box, use the nudge buttons to add/delete
columns in the grid
3. Under the Row Guides section, in the Rows text box, use the nudge buttons to add/delete rows in the
grid
4. To display a line between column and row borders, select Add center guide between columns and
rows
5. When done, click OK
The grid is created.
Inserting and Removing Pages
Once you have begun working on a publication, you may decide that the number of pages originally
assigned to the document is either not enough or too many. You can adjust the number of pages, however,
by inserting or removing pages.
Inserting Pages
Removing Pages
Inserting Pages
or as individual pages.
Inserting Pages: Individual Pages
1. Place the insertion point in the page before or after where the additional pages will be inserted
2. From the Insert menu, select Page...
The Insert Page dialog box appears.
3. In the Number of new pages text box, type the number of pages to be inserted
4. To insert the pages before the currently displayed page, select Before current page
To insert the pages after the currently displayed page, select After current page
Balaji Institute of Technology and Science 59
ITWS Lab Department of Computer Science and Engineering
5. Click OK
The pages are inserted.
When working with the Two-Page Spread view, you can insert new pages to the left or right of the two-page
spread or between the two pages.
1. Place the insertion point in the page before or after where the additional pages will be inserted
2. From the Insert menu, select Page...
The Insert Page dialog box appears.
3. In the Number of new pages text box, type the number of pages to be inserted
4. To insert the pages before the left page, select Before left page
To insert the pages after the right page, select After right page
To insert the pages between the left and right pages, select Between pages
5. Click OK
The pages are inserted.
Removing Pages
or as individual pages.
Removing Pages: Individual Pages
1. Place the insertion point in the page to be removed
2. From the Edit menu, select Delete Page...
The page is removed.
1. Place the insertion point in the page(s) to be removed
Balaji Institute of Technology and Science 60
ITWS Lab Department of Computer Science and Engineering
2. From the Edit menu, select Delete Page...
The Delete Page dialog box appears.
3. To delete both displayed pages, select Both pages
To delete only one of the displayed pages, select Left page only or Right page only
The page(s) are removed.
In Microsoft Office Publisher 2003, you can create hyperlinks to files, Web pages, e-mail addresses, and
other pages in a Web publication by using the Insert Hyperlink button on the Standard toolbar.
You can also create a hyperlink to a specific location on a Web page (sometimes called inserting a
See Also section, which is visible when you are connected to the Internet.
To follow a hyperlink after you insert it, hold down CTRL while you click the linked text or picture.
Create a hyperlink to a file
1. Select either text or a picture.
2. On the Standard toolbar, click Insert Hyperlink .
3. Under Link to, click Existing File or Web Page.
4. Do one of the following:
To select a file from your My Documents folder, click Current Folder.
To select a file that you were recently working in, click Recent Files.
5. Browse to and select the file or page that you want.
Create a hyperlink to a Web page
2. Select the URL of the Web page, and then press CTRL+C to copy it.
3. In Publisher, select either text or a picture.
4. On the Standard toolbar, click Insert Hyperlink .
5. Under Link to, click Existing File or Web Page.
6. Click in the Address box, and then press CTRL+V to paste the URL.
Balaji Institute of Technology and Science 61
ITWS Lab Department of Computer Science and Engineering
Note If you recently visited the Web page that you want to link to, you can start with step 3. In the Insert
Hyperlink dialog box, click Browsed Pages. In the list of Web pages, click the URL that you want.
1. Select either text or a picture.
2. On the Standard toolbar, click Insert Hyperlink .
4. Either type the e-mail address that you want in the E-mail address box, or select an e-mail address
from the Recently used e-mail addresses box.
5. In the Subject box, type the subject of the e-mail message.
Note Some Web browsers and e-mail programs might not recognize the subject line.
1. Select either text or a picture.
2. On the Standard toolbar, click Insert Hyperlink .
3. Under Link to, click Place in This Document.
4. Select the page that you want.
Create a hyperlink to a new file
1. Select either text or a picture.
2. On the Standard toolbar, click Insert Hyperlink .
3. Under Link to, click Create New Document.
4. Type the name of the new file, including the three-letter extension (such as .pub, .doc, or .xls).
5. Do one of the following:
If you know the full path of the location where you want to create the new file, you can
include the full path with the name.
If you don't know the full path, click Change, and then browse to the location that you want,
select it, and then click OK.
6. Click either Edit the new document later or Edit the new document now.
Publish a Publisher Web site
After you have created a Web publication in Publisher, your next step is to publish it. You can publish a
Web site to a Web server (Web server: A computer that hosts Web pages and responds to requests from
browsers. Also known as an HTTP server, a Web server stores files whose URLs begin with http://.), a
network server, a File Transfer Protocol (FTP) (FTP: A communication protocol that makes it possible for a
user to transfer files between remote locations on a network. This protocol also allows users to use FTP
commands, such as listing files and folders, to work with files on a remote location.) server, or to a folder on
Publish a Web site to a location on the Internet or on a network
Balaji Institute of Technology and Science 62
ITWS Lab Department of Computer Science and Engineering
To publish your Web site on the World Wide Web (WWW) (World Wide Web (WWW): The multimedia
branch of the Internet that presents not only text, but also graphics, sound, and video. On the Web, users can
easily jump from item to item, page to page, or site to site by using hyperlinks.), you need to subscribe to a
Web hosting service. A Web hosting service provides Internet access and storage space on Web servers.
provides access to the Internet for such things as electronic mail, chat rooms, or use of the World Wide
Web. Some ISPs are multinational, offering access in many locations, while others are limited to a specific
region.) or system administrator for the Uniform Resource Locator (URL) (Uniform Resource Locator
(URL): An address that specifies a protocol (such as HTTP or FTP) and a location of an object, document,
World Wide Web page, or other destination on the Internet or an intranet, for example:
http://www.microsoft.com/.) of the Web site where you can save files.
1. On the File menu, click Publish to the Web.
2. In the File name box in the Publish to the Web dialog box, type the URL of the Web or network
server where you want to save your Web site, and then click Save.
3. If prompted, type your user name and password, and then click OK.
The directory associated with your URL will appear in the Publish to the Web dialog box.
4. Double-click the folder where you want to save your Web site.
5. In the File name box, select index as the default name for your home page, and then click Save.
6. When prompted, click OK.
Publish a Web site using FTP
Before following this procedure, contact your Internet Service Provider or system administrator to get the
information you need to publish to an FTP (FTP: A communication protocol that makes it possible for a
user to transfer files between remote locations on a network. This protocol also allows users to use FTP
commands, such as listing files and folders, to work with files on a remote location.) site. You also have to
create an FTP site in FTP Locations.
How?
1. On the File menu, click Publish to the Web.
2. In the Save in box, click FTP Locations.
4. Enter the information you received from your Internet Service Provider, and then click OK.
5. Click Cancel.
1. On the File menu, click Publish to the Web.
2. In the Save in box, click FTP Locations.
3. In the list of FTP sites, double-click the site you want, and then double-click the folder where you
want to publish your Web site.
4. Click Save.
Publish a Web site to a folder on your computer
1. On the File menu, click Publish to the Web.
Balaji Institute of Technology and Science 63
ITWS Lab Department of Computer Science and Engineering
2. In the Save in list, in the Publish to the Web dialog box, click the drive or folder where you want to
3. Do one of the following:
In the folder list, double-click the folder where you want to publish your Web site.
Click Create New Folder to create a new folder, and then type a name for the new folder
in the Name box.
5. Click Save.
Note If your Internet Service Provider (ISP) requires you to use a specific program to upload your Web
site, or if you are publishing your Web site to a corporate intranet, you may need to save a version of your
Web site in a specific HTML (HTML: The standard markup language used for documents on the World
Wide Web. HTML uses tags to indicate how Web browsers should display page elements such as text and
graphics and how to respond to user actions.) file format and follow a different procedure to publish your
Web site.
Create a website for your college. The website should have the following pages
1. Homepage which describes the college website
2. About Us page which tells about the college vision, when it was established...etc
3. Departments page which describes the departments in the college
4. Separate pages for at least two departments of your college
5. Contact page which contains address and contact information about the college
Guidelines for the website are given below:
NOTE: Resources like and images and documents are available in Website Content Folder
Homepage
Balaji Institute of Technology and Science 64
ITWS Lab Department of Computer Science and Engineering
Replace this image with
logo.jpg
Replace this image with
building.jpg
Balaji Institute of Technology and Science 65
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 66
ITWS Lab Department of Computer Science and Engineering
to the corresponding
department pages
Balaji Institute of Technology and Science 67
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 68
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 69
ITWS Lab Department of Computer Science and Engineering
Balaji Institute of Technology and Science 70
ITWS Lab Department of Computer Science and Engineering
LaTeX
What is LaTeX?
A typesetting program written by Leslie Lamport of MIT.
Pronounced “Lah-tek, or Lay-tek”
Uses TeX engine written by Donald E. Knuth
Designed for producing beautiful books, thesises, papers, articles...
De facto standard for writing academic papers
Current version LaTeX2e
Why LaTeX, not MS Word?
FAST professional output – highest quality
Platform, version independent (Unix, Win)
Device independent output (.dvi)
Pre-set standard formats for all types of documents
Freely available
Secure – never lose your files, both old and new!
Concentrate on content, leave the style to LaTeX.
Source code for large docs comparatively small.
Need other software for extensibility.
Need to access CTAN for modules.
Complex tables are not easy JNot WYSIWYG but WYSIWYM !
Rather steep learning curve - need to remember commands
Encourages structured writing – counter-intuitive for lay users!
Not integrated with other MS Office products
Where to get LaTeX?
Linux:
Almost all distributions bundle LaTeX.
Windows packages and frontends.
MikTeX
WinShell/TeXnicCenter/LEd/Texmaker
LyX (for win and Lin as well)
Where to get help?
newsgroup comp.text.tex
LaTeX package documentation
Balaji Institute of Technology and Science 71
ITWS Lab Department of Computer Science and Engineering
LaTeX package structure
A collection of defined commands
Classes and packages.AMS-TeX – a collection of extensions to TeX with more
Markup language
Similar to “tagging” and “Markup” (think HTML!)
Create (tex) > Compile (tex) > Run/view (dvi/pdf/ps)
LaTeX Skeleton
% my first LaTeX file
\documentclass[options]{class}
\begin{document}
Hello, world!
\end{document}
How To Run LaTeX
Compose/Edit --> TeXnicCenter myfile.texCompile --> LaTeX myfile.tex
View --> xdvi myfile.dvi (UNIX)
yap myfile.dvi (Windows)
Dvi--> PostScript dvips myfile
View PostScript gv myfile (UNIX)
Use gsview (Windows)
Syntax
Latex Flowchart
Balaji Institute of Technology and Science 72
ITWS Lab Department of Computer Science and Engineering
Resolve Edit myfile Resolve
cross- compile
eference error
LaTeX myfile
myfile.dvi
xdvi myfile yap myfile
(UNIX) (Windows)
dvips myfile myfile.ps
print
Balaji Institute of Technology and Science 73
ITWS Lab Department of Computer Science and Engineering
The syntax of LaTeX
classes and environments
Families,
Ex - \author{R.Raghuram}
• \title{how to learn latex}
• \section{section name}
Allenvironments begin with “\begin{env name}”
Special Characters - #$%^&_{}~\ Anything that begins with ‘%’ is a comment. % Anything after this symbol is ignored File formats encountered in Latex .tex - LaTeX input file. Can be compiled with latex. .sty - LaTeX Macro package. .cls - Class files define what your document looks like. They are selected with the \documentclass cmd .dvi - Device Independent File. .log - Gives a detailed account of what happened during the last compiler run. .toc - Stores all your section headers. It gets read in for the next compiler run and is used to produce the table of content. Important “layout” commands in Latex \documentclass[options]{class} \title \maketitle % commit title info to paper. \begin{document}$$;$$\end{document} \begin{abstract}$$;$$\end{abstract} \include{filename} % call another file here. $$;$$ \usepackage{packagename} \section{sectionname} Important formatting commands \underline{text} \emph{text} % set text to italics \textbf{text} % set text to bold \bfseries % switches to bold from here. Some more formatting! Balaji Institute of Technology and Science 74 ITWS Lab Department of Computer Science and Engineering Some exemplary examples Balaji Institute of Technology and Science 75 ITWS Lab Department of Computer Science and Engineering How to solve problems Look at the error LaTeX gave you. It will have a line number which will help you find the error. Common mistakes: Mismatched \begin{}/\end{} blocks Mismatched {/} Mismatched$, , or or
Misspelled keywords
Sometimes lines are too long. This isn’t fatal but looks bad. LaTeX outputs a warning with
a line number so you can fix it.
Balaji Institute of Technology and Science 76
ITWS Lab Department of Computer Science and Engineering
Microsoft Word
Sun rolls out network products
BY Brian Robinson
3
June 2nd 2005
O
1
fficials at SUN MICROSYSTEMS INC.. introduced a slew of products to boost delivery of network
SUN MICROSYSTEMS INC.
SUN MICROSYSTEMS INC
services, including a new file system for the Solaris operating system, a second release of an identity
management solution and a subscription-based model that assigns a single price to more than 100
2 services.
Sun's new Dynamic File System provides "16 billion times more capacity" than current file 4
systems, said Sun's chief executive officer Scott McNealy, making it infinitely scalable.
5
The file system, which is included as a part of S o l a r i s 1 0 , also automates many of the tasks that
systems administrators now have to do by hand. Creating and growing file systems has been cut from 28 to
just five separate tasks, for example, while adding mirrored file systems and storage space for users will
6 now take as little as 10 seconds.
7
The second release of the identity-management solution has three new products based on the
software acquired by Sun with its recent purchase of Waveset Technologies Inc. The Sun Java
System Identity Manager combines user provisioning with metadirectory capabilities, which Sun
claims is an industry first, enabling administrators to manage identity permissions and profiles and
simultaneously synchronize services for those directories across the enterprise.
The other products include an access manager to help manage access to internal and external Web-based
resources, and an enterprise version of the Sun Java System Directory Server that includes
, load balancing, security and integration with Microsoft Corp.'s Active Directory.
8
Sun's Preventive Services is aimed at the data center and is an attempt at what McNealy called a
9 more simplified way of pricing services than through complex outsourcing contracts. It includes a
portfolio of more than 100 services that managers can use to find issues that might affect network
performance and for which they pay one price.
I
n general, many of the new announcements also included references to other kinds of subscription-based
pricing, which Sun officials see as a trend among users who increasingly don't want to own the technology
themselves.
Other items introduced June 1 included an array of low-cost storage products, software to collect and
10 manage data produced by radio-frequency identity systems and a pricing system aimed specifically at Third
World and developing markets through which Sun's Java Enterprise System would be sold on a per-citizen
basis using the United Nation's ranking for a country's development status.
Robinson is a freelance journalist based in Portland, Ore. He can be reached at hullite@mindspring.com.
GIET 11
Top
Balaji Institute of Technology and Science 77
ITWS Lab Department of Computer Science and Engineering
Set font to:
a. Heading 1 + 16 pt, Bold, Black 10
i. Select the text you want to change.
ii. On the Format menu open, click Styles and Formatting and select Heading1.
iii. On the Format menu, click Font, and then click the Font tab and modify the Font
Size, Style and Color.
b. Normal + Verdana, 9.5 pt, Bold, Italic, Dark Blue
i. Select the text you want to change.
ii. On the Format menu open, click Styles and Formatting and select Normal.
iii. On the Format menu, click Font, and then click the Font tab and modify the Font,
Size, Style and Color.
c. "nd" as superscript
i. Select the text you want to change.
ii. On the Format menu, click Font, and then click the Font tab and select the Effect.
2. Drop cap
a. Click the paragraph that you want to begin with a "drop cap," a large dropped initial capital
letter.
b. On the Format menu, click Drop Cap.
c. Click Dropped.
3. Set font to:
a. Emboss and Text Color white
i. Select the text you want to change.
ii. On the Format menu, click Font, and then click the Font tab and select the Effect
and Font Color.
i. Select the text you want to change.
iii. Select Color and click OK.
iv. Alternatively, use the shading button in the toolbar. Select the text and click on the
toolbar.
4. Set font to:
a. Normal + Verdana, Bold, Italic, Black
i. Select the text you want to change.
ii. On the Format menu open, click Styles and Formatting and select Normal.
iii. On the Format menu, click Font, and then click the Font tab and modify the Font,
Size, Style and Color.
5.Set font to:
b. Raised and Expanded character spacing
i. Select the text you want to change.
ii. On the Format menu, click Font, and then click the Character Spacing tab and
Click Expanded in the Spacing box, and then specify how much space you want in
the By box.
c. Border the given text
i. Select the text you want to change.
ii. On the Format menu, click Borders and Shading, and then click the Borders tab.
iii. Click Text under Apply to.
Balaji Institute of Technology and Science 78
ITWS Lab Department of Computer Science and Engineering
6Strikethrough Font effect
d. Select the text you want to change.
e. On the Format menu, click Font, and then click the Font tab and select the Effect.
7Underline styling
f. Select the text you want to change.
g. On the Format menu, click Font, and then click the Font tab and select the Underline
Styles.
8Outline Font
h. Select the text you want to change.
i. On the Format menu, click Font, and then click the Font tab and select the Effect.
9Paragraph indentation
j. Justify With 1 Inch Right Margin
i. Select the paragraphs in which you want to change spacing.
ii. On the Format menu, click Paragraph, and then click the Indents and Spacing tab.
iii. Modify Alignment, Indentation and spacing.
iv. View in the Preview section before applying.
v. Alternatively, the toolbar can be used for paragraph alignment.
k. Left Align
l. Justify With 1 Inch Right Margin
m. Center Align
n. Right Align
10Drop Cap Column
o. Click the paragraph that you want to begin with a "drop cap," a large dropped initial capital
letter.
p. On the Format menu, click Drop Cap.
q. Right Click and select Hyperlink.
r. Under Link to, click Place in This Document. In the list, select the heading or bookmark
11Insert Date And Time In Footer
s. On the View menu, click Header and Footer to open the header or footer area on a page.
t. On the Insert menu, click Date and Time. Select the Date format and Check/Uncheck
Update Automatically option and click OK.
u. When you finish, click Close on the Header and Footer toolbar
Balaji Institute of Technology and Science 79
ITWS Lab Department of Computer Science and Engineering
JNT University
1 1
Job Performance Review Guide
Employee
Employee Review
Name Period
Departm Mana
ent ger
Performance goals and objectives
Zero to 2 months 2 to 4 months 4-6 months
2
Become familiar with your department’s Make certain defined goals and criteria Review performance goals to see if you
business goals. are realistic. Renegotiate if necessary. are on target. Reprioritize work
accordingly.
Work with your manager to define and Are you focusing your time on the goals
document your goals. Include what you you committed to? If not, either work
review, activities needed to accomplish or reevaluate how you spend your time.
results, and success criteria.
3
Skills and knowledge development
Zero to 2 months 2 to 4 months 4-6 months
a. Understand the specific skills and d. Attend one of the sessions in the f. Attend at least one more session in the
knowledge you need. Use the job Administrator certification program. See Administrator certification program. 4
profile as your guide. the training resource site for courses.
g. Create a timeline with associated tasks
b. Build a skill development plan based on e. Review your development plan and that you will follow in order to attain
the goals agreed to by you and suggested curriculum for additional
development plan.
orientation.
NOTES/ACTIONS
5
Processes and Methods
Zero to 2 months 2 to 4 months 4-6 months
6
Familiarize yourself with work Identify and eliminate unnecessary
Seek to simplify
the people who
functionality in
common work
processes and methods used in your variation in the way you perform work
processes in
Get to know
order to cut
work cross-
cycle time.
job. Be clear on who owns those
processes.
processes.
any work
processes and how you can support
process goals. Ensure that your work responsibilities
are clear, defined, and realistic.
Set clear timelines for task due dates.
Keep timelines up to date.
Feedback1
Zero to 2 months 2 to 4 months 4-6 months
Are you getting the feedback you need? Is Are you giving feedback to others who
feedback timely, specific, and frequent? need it?
Understand the different types of feedback Compare actual performance and expected
and the ways in which you will receive performance. Compare actual and expected
feedback. performance.
7
1
8
Balaji Institute of Technology and Science 80
ITWS Lab Department of Computer Science and Engineering
HELP
1. Table:
a. Border Style
i. Select table
ii. On the Format menu, click Borders and Shading, and then click the Borders tab
iii. Click Paragraph under Apply to, click Options, and then select the options you
want.
b. Cells Split
i. On the Table menu, click Split Cells
ii. Select the number of columns or rows you want to split the selected cells into.
c. Cells Merge
i. Select cell to merge
ii. On the Table menu, click Merge Cells
.
2. Paragraph Border
a. Select Paragraph
b. On the Format menu, click Borders and Shading, and then click the Borders tab
c. Click Paragraph under Apply to, click Options, and then select the options you want.
3. Bullets and numbering
a. Select the text that you want to change
b. On the Formatting toolbar, click Bullets and Numbering
c. In numbers tab choose style and click on continue previous list.
4. Paragraph Bordering
a. Select Paragraph
b. On the Format menu, click Borders and Shading, and then click the Borders tab
c. Click Paragraph under Apply to, click Options, and then select the options you want.
5. Bullets
a. Select the text that you want to change
b. On the Formatting toolbar, click Bullets and Numbering
c. In bulleted tab choose style.
6. Text Direction
a. Click the table cell that contains the text you want to change
b. On the Format menu, click Text Direction and Click the orientation you want
7. Cell Alignment
a. Click the cell that contains text you want to align
b. On the Tables and Borders toolbar, select the option for the horizontal and vertical
alignment you want— for example, Align Bottom Center or Align Top Right
8. Footnote
a. On the Insert menu, point to Reference, and then click Footnote
b. In the Number format box, click the format you want and click Insert.
Balaji Institute of Technology and Science 81
ITWS Lab Department of Computer Science and Engineering
1
Feedback Form
Date: 9/11/2012
Faculty Name: Vengal Rao Subject: DSP Year/Semester: III/IV 1st Sem
Optional
5
Student Name: Roll Number: Branch: CSE
Review Guidelines 2
3
2
mplete this peer review, using the following scale: NA = Not Applicable
1 = Unsatisfactory
2 = Marginal
3 = Meets Requirements
4 = Exceeds Requirements
5 = Exceptional
Evaluation
(5) = (4) = Exceeds (3) = Meets (2) = (1) =
Exceptional Requirements Requirements Marginal Unsatisfactory
quired Skills And Knowledge in the
ass
sponse To Questions
ility To Learn And Teach New Skills 4
glish Speaking Skills
aking Students To Involve In The
ass
Balaji Institute of Technology and Science 82
ITWS Lab Department of Computer Science and Engineering
1. Insert Date from “Date and Time” Option.
2. Form Field – Text Form Field
a. To display the Forms toolbar, point to Toolbars on the View menu, and then click Forms.
b. In the document, click where you want to insert the form field.
c. Click Text Form Field.
3. Form Field – Drop-Down Form Field
a. In the document, click where you want to insert the form field.
b. Click Drop-Down Form Field.
c. If needed, a user can scroll through the list to view additional choices.
d. To edit these fields, you must use the Form Field Options button on the Forms toolbar.
4. Form Field – Check Box Form Field
a. In the document, click where you want to insert the form field.
b. Click Check Box Form Field.
c. To edit these fields, you must use the Form Field Options button on the Forms toolbar.
5. Mail Merge
a. On the Tools menu, point to Letters and Mailings, and then click Mail Merge.
b. Word displays the Mail Merge task pane.
c. Select type as “Letters” and click “Next: Starting Document”.
d. Click Use the current document, and Click “Next: Select recipients”.
e. Under Select recipients, click Use an existing list.
f. Click Browse.
g. In the Select Data Source dialog box, locate and click the data source you want.
h. Browse for the given “List.txt” file., and Click Open.
i. All of the entries in the data source appear in the Mail Merge Recipients dialog box, where
you can refine the list of recipients to include in the merge.
j. Click Next: Write your letter.
k. Click on the location where you want to put a merge field. Click on more items.
l. Select and Insert the merge field at that location.
m. Click Next: Preview your letters.
n. To preview the items in order, click the arrow buttons.
o. To exclude a particular recipient from the merge, click Exclude this recipient.
p. Click Next: Complete the merge.
q. You can either print all the letters or Edit individual letters
i. Click Edit individual letters.
ii. To merge all the documents, click All.
iii. Save it to a separate document for future use.
Note: Before you can make a form available to users, you must protect it by clicking Protect Form on
the Forms toolbar. Protection allows users to fill in the form but prevents them from changing the
form's layout and its standard elements.
Balaji Institute of Technology and Science 83
ITWS Lab Department of Computer Science and Engineering
The Title Goes Here With Each Initial Letter Capitalized
Author's Name
1
Replace this text with Author's Affiliation
4 INTRODUCTION ...................................................................................................................................... 84
SECOND LEVEL HEADING (HEADING 2) WITH EACH INITIAL LETTER CAPITALIZED ................................ 85
Third Level Heading (Heading 3) With Each Initial Letter Capitalized ............................................. 85
ACKNOWLEDGMENTS ....... ERROR! BOOKMARK NOT DEFINED.ERROR! BOOKMARK NOT DEFINED.
REFERENCES ........................ ERROR! BOOKMARK NOT DEFINED.ERROR! BOOKMARK NOT DEFINED.
Chapter 1
must use the style “INTRODUCTION.”
Abstract Otherwise, your paragraph spacing will
be off.
2 Do not replace the word “abstract,” but
do replace the rest of this text. If you FIRST LEVEL HEADING
must insert a hard line break, please use2
Shift+Enter rather than just tapping your
"Enter" key. You may want to print this This is the standard font and layout for
page and refer to it as a style sample the individual paragraphs. The style is
before you begin working on your paper. called "Paragraph." Replace this text
with your text. The "Enter" key will
2 INTRODUCTION take you to a new paragraph. If you
need to insert a hard line break within
Balaji Institute of Technology and Science 84
ITWS Lab Department of Computer Science and Engineering
the paragraph, please use Shift+Enter, the entire line, then use copy and paste
rather than just tapping the "Enter" key. to place the equation in the new location.
This is the paragraph spacing that occurs x
(1)
when you use the Enter key. y 3
Second Level Heading This is example text$$;$$you can type
(Heading 2) With Each Initial anything you want. This is example text;
Letter Capitalized you can type anything you want. This is
This is the standard font and layout for example text, you can type anything you
the individual paragraphs. The style is want. This is example text, you can type
called "Paragraph." Replace this text anything you want. This is example text;
with your text. The "Enter" key will you can type anything you want. This is
take you to a new paragraph. If you example text$$;$$you can type anything you
need to insert a hard line break within want., This is example text$$;$$you can type
the paragraph, please use Shift+Enter, anything you want. This is example text;
rather than just tapping the "Enter" key. you can type anything you want. This is
example text$$;$$you can type anything you
This is the paragraph spacing that occurs want. This is example text$$;$$you can type
when you use the Enter key. anything you want.
With Each Initial Letter Insert an image / table / object here.
Capitalized
This is the standard font and layout for
the individual paragraphs. The style is This is example text$$;$$you can type
called "Paragraph." Replace this text anything you want. This is example text;
with your text. The "Enter" key will you can type anything you want. This is
take you to a new paragraph. If you example text$$;$$you can type anything you
need to insert a hard line break within want. This is example text$$;$$you can type
the paragraph, please use Shift+Enter, anything you want. This is example text;
rather than just tapping the "Enter" key. you can type anything you want. This is
example text$$;$$you can type anything you
This is the paragraph spacing that occurs want. This is example text$$;$$you can type
when you use the Enter key. anything you want. This is example text;
you can type anything you want. This is
REPLACE THIS TEXT WITH FIGURE example text$$;$$you can type anything you
GRAPHIC want. This is example text$$;$$you can type
FIGURE 1. This is the Style for Figure anything you want.
Captions. Center this if it doesn’t run for
more than one line.
To insert a footnote, use the "Insert"
menu, select "Footnote", and click "OK"
Below is an example equation created
with Word Equation Editor. To move
this equation, highlight the entire line,
then use cut and paste to the new
location. To use this as a template, select
Balaji Institute of Technology and Science 85
ITWS Lab Department of Computer Science and Engineering
Help
1. Applying your new style for Text.
a. Click Styles and Formatting on the Formatting toolbar.
b. In the Styles and Formatting task pane, click New Style.
c. In the Name box, type a name for the style.
d. In the Style type box, click Paragraph, Character, Table, or List to
specify the kind of style you are creating.
e. Select the options that you want, or click Format to see more options.
2. Applying your new style for Text or Apply Existing style for text.
3. Inserting Microsoft Equation
a. Click where you want to insert the equation.
b. On the Insert menu, click Object, and then click the Create New tab.
c. In the Object type box, click Microsoft Equation 3.0. (If Microsoft
Equation Editor is not available, you may need to install it.)
d. Click OK.
b. On the Insert menu, point to Reference, and click Index and Tables.
d. To use one of the available designs, click a design in the Formats box.
e. Click Options.
f. Under Available styles, find a style you've applied to headings in your
document.
g. Under TOC level, to the right of the style name, enter a number from 1 to
9 to indicate the level you want that heading style to represent.
Note If you want to use only custom styles, remove the TOC level numbers for
the built-in styles, such as Heading 1.
Balaji Institute of Technology and Science 86
ITWS Lab Department of Computer Science and Engineering
MICROSOFT Excel
Microsoft Excel is a spreadsheet program. It features an intuitive interface, calculation and
graphing tools. These tools could be used for business financial analysis and other
applications to date. In this module you will master Microsoft Excel.
Merge cells
When you merge two or more adjacent cells, the cells become one merged cell, and
the contents of the upper-left cell are displayed in the center of the merged cell, as
shown in the following example.
Text spread and centered over multiple cells
Important Only the data in the upper-left cell of a range (range: Two or more cells
on a sheet. The cells in a range can be adjacent or nonadjacent.) of selected cells
will remain in the merged cell. Data in other cells of the selected range will be
deleted.
1. If the data that you want to display in the merged cell is not in the upper-left
cell, do the following:
1. Select the data that you want to display in the merged cell, and then click
Copy on the Standard toolbar.
2. Select the upper-left cell of the range of adjacent cells that you want to
merge, and then click Paste on the Standard toolbar.
2. Select the cells that you want to merge.
Note The cells that you select must be adjacent.
3. On the Formatting toolbar (toolbar: A bar with buttons and options that you
can use to carry out commands. To display a toolbar, point to Toolbars on the
View menu. If you don't see the button you want, click the arrows at the right
end of the toolbar.), click Merge and Center .
The cells will be merged in a row or column, and the cell contents will be
centered in the merged cell.
Note If the Merge and Center button is unavailable, the selected cell may be in
editing mode. To cancel editing mode, press ENTER.
5. To change the text alignment in the merged cell, select the cell, and then click
Align Left or Align Right on the Formatting toolbar.
Balaji Institute of Technology and Science 87
ITWS Lab Department of Computer Science and Engineering
Enabling Border options
Using predefined border styles, you can quickly add a border around cells or
ranges (range: Two or more cells on a sheet. The cells in a range can be adjacent or
1. To apply a new or different border style, click the arrow next to Borders on the
Formatting toolbar, and then choose a border style from the palette.
Tip To apply a custom border style or a diagonal border, click Cells on the
Format menu. On the Border tab, click the line style and color that you want,
and then click one or more buttons to indicate the border placement. Two
diagonal border buttons are available under Border.
2. To remove cell borders, click the arrow next to Borders on the Formatting
toolbar, and then click No Border on the palette.
AutoFill Data
Automatically repeat items already entered in the column
If the first few characters that you type in a cell match an existing entry in that
column, Microsoft Excel automatically enters the remaining characters for you. Excel
automatically completes only those entries that contain text or a combination of text
and numbers. Entries that contain only numbers, dates, or times are not completed.
Do one of the following:
1. To accept the proposed entry, press ENTER.
2. The completed entry exactly matches the pattern of uppercase and lowercase
letters of the existing entry.
3. To replace the automatically entered characters, continue typing.
4. To delete the automatically entered characters, press BACKSPACE.
Use the fill handle to fill data
You can use the Series command (point to Fill on the Edit menu, and then click
Series) to fill data into worksheet cells. You can also have Excel automatically
continue a series of numbers, number and text combinations, dates, or time periods,
based on a pattern that you establish. However, to quickly fill in several types of
data series, you can select cells and drag the fill handle (fill handle: The small black
square in the lower-right corner of the selection. When you point to the fill handle,
the pointer changes to a black cross.) .
The fill handle is displayed by default, but you can hide it.
1. On the Tools menu, click Options.
2. On the Edit tab, do one of the following:
To hide the fill handle, clear the Allow cell drag and drop check box.
To display the fill handle, select the Allow cell drag and drop check
box.
To avoid replacing existing data when you drag the fill handle, make sure that the
Alert before overwriting cells check box is selected. If you don't want to get a
message about overwriting nonblank cells, you can clear this check box.
Balaji Institute of Technology and Science 88
ITWS Lab Department of Computer Science and Engineering
1. Select the cells that contain the data that you want to fill into adjacent cells.
2. Drag the fill handle (fill handle: The small black square in the lower-right corner
of the selection. When you point to the fill handle, the pointer changes to a black
cross.) across the cells that you want to fill.
3. You can use the Auto Fill Options button , which appears after you drag the
fill handle, to choose how to fill the selection. For example, you can choose Fill
Formatting Only or Fill Without Formatting.
1. Select the cell that contains the formula that you want to fill into adjacent cells.
2. Drag the fill handle (fill handle: The small black square in the lower-right corner
of the selection. When you point to the fill handle, the pointer changes to a black
cross.) across the cells that you want to fill.
3. You can use the Auto Fill Options button , which appears after you drag the
fill handle, to choose how to fill the selection. For example, you can choose Fill
Formatting Only or Fill Without Formatting.
Fill in a series of numbers, dates, or other built-in series items
Using the fill handle (fill handle: The small black square in the lower-right corner of
the selection. When you point to the fill handle, the pointer changes to a black
cross.), you can quickly fill cells in a range with a series of numbers or dates or with
a built-in series for days, weekdays, months, or years.
1. Select the first cell in the range that you want to fill.
2. Type the starting value for the series.
3. Type a value in the next cell to establish a pattern.
For example, if you want the series 1, 2, 3, 4, 5..., type 1 and 2 in the first two
cells. If you want the series 2, 4, 6, 8..., type 2 and 4. If you want the series 2,
2, 2, 2..., you can leave the second cell blank.
More examples of series that you can fill
When you fill a series, the selections are extended as shown in the following
table. Items separated by commas are in placed in individual adjacent cells.
Initial selection Extended series
1, 2, 3 4, 5, 6,...
4. Select the cell or cells that contain the starting values.
5. Drag the fill handle across the range that you want to fill.
To fill in increasing order, drag down or to the right. To fill in decreasing order,
drag up or to the left.
Fill data by using a custom fill series
To make entering a particular sequence of data (such as a list of names or sales
regions) easier, you can create a custom fill series. A custom fill series can be based
on a list of existing items on a worksheet, or you can type the list from scratch.
Use a custom fill series based on an existing list of items
1. On the worksheet, select the list of items that you want to use in the fill series.
2. On the Tools menu, click Options, and then click the Custom Lists tab.
3. Verify that the list of items that you selected is displayed in the Import list
from cells box, and then click Import.
The items in the list that you selected are added to the Custom lists box.
4. On the worksheet, click a cell, and then type the item in the custom fill series
that you want to use to start the list.
Balaji Institute of Technology and Science 89
ITWS Lab Department of Computer Science and Engineering
5. Drag the fill handle (fill handle: The small black square in the lower-right corner
of the selection. When you point to the fill handle, the pointer changes to a black
cross.) across the cells that you want to fill.
Use a custom fill series based on a new list of items
1. On the Tools menu, click Options, and then click the Custom Lists tab.
2. In the Custom lists box, click New list, and then type the entries in the List
entries box, beginning with the first entry.
Press ENTER after each entry.
3. When the list is complete, click Add.
4. On the worksheet, click a cell, and then type the item in the custom fill series
that you want to use to start the list.
5. Drag the fill handle across the cells that you want to fill.
Add, change, or remove conditional formats
1. Select the cells for which you want to add, change, or remove conditional
formatting (conditional format: A format, such as cell shading or font color, that
Excel automatically applies to cells if a specified condition is true.).
2. On the Format menu, click Conditional Formatting.
3. Do one of the following:
1. Do one of the following:
To use values in the selected cells as the formatting criteria, click Cell Value
Is, select the comparison phrase, and then type a constant (constant: A
value that is not calculated and, therefore, does not change. For example, the
number 210, and the text "Quarterly Earnings" are constants. An expression,
or a value resulting from an expression, is not a constant.) value or a
formula. If you enter a formula, start it with an equal sign (=).
To use a formula as the formatting criteria (to evaluate data or a condition
other than the values in selected cells), click Formula Is and then enter the
formula that evaluates to a logical value of TRUE or FALSE.
2. Click Format.
3. Select the formatting you want to apply when the cell value meets the
condition or the formula returns the value TRUE.
4. To add another condition, click Add, and then repeat steps 1 through 3.
You can specify up to three conditions. If none of the specified conditions are
true, the cells keep their existing formats.
Note Using multiple conditions If more than one specified condition is true,
Microsoft Excel applies only the formats of the first true condition, even if more
than one condition is true.
Copy formats to other cells
1. Select the cells that have the conditional formats you want to copy.
2. On the Formatting toolbar (toolbar: A bar with buttons and options that you
use to carry out commands. To display a toolbar, click Customize on the
Tools menu, and then click the Toolbars tab.), click Format Painter ,
and then select the cells you want to format.
Change or remove a conditional format
Do one or more of the following:
1. To change formats, click Format for the condition you want to change.
2. To reselect formats on the current tab of the Format Cells dialog box, click
Clear and select new formats.
Balaji Institute of Technology and Science 90
ITWS Lab Department of Computer Science and Engineering
3. To remove one or more conditions, click Delete, and then select the check
box for the conditions you want to delete.
Tip
To remove all conditional formats as well as all other cell formats for selected
cells, point to Clear on the Edit menu, and then click Formats.
Display numbers as dates or times
1. Select the cell or range (range: Two or more cells on a sheet. The cells in a
range can be adjacent or nonadjacent.) or cells that you want to format.
2. On the Format menu, click Cells.
3. On the Number tab, in the Category list, click Date or Time.
4. In the Type list, click the format that you want to use.
Dates or times that you type into formatted cells will be displayed in the format
that you selected.
Custom date and time codes
Days, months, and years If you use "m" immediately after the "h" or "hh" code
or immediately before the "ss" code, Microsoft Excel displays minutes instead of the
month.
To display Use this code
Months as 1–12 m
Hours, minutes, and seconds
To display Use this code
Hours as 0–23 H
1.AM and PM If the format contains an AM or PM, the hour is based on the 12-
hour clock, where "AM" or "A" indicates times from midnight until noon and "PM"
or "P" indicates times from noon until midnight. Otherwise, the hour is based on
the 24-hour clock. The "m" or "mm" code must appear immediately after the "h"
or "hh" code or immediately before the "ss" code$$;$$otherwise, Microsoft Excel
displays the month instead of minutes.
2.When you try to undo a date or time format by selecting General in the
Category list, Excel displays a number code. When you enter a date or time
again, Excel displays the default date or time format. To enter a specific date or
time format, such as January 2005, you may want to format it as text by
selecting Text in the Category list.
You can add shading to cells by filling them with solid colors or specific patterns.
1. Select the cells or ranges (range: Two or more cells on a sheet. The cells in a
2. Do one of the following:
To fill cells with a solid color, click the arrow next to Fill Color on the
Formatting toolbar (toolbar: A bar with buttons and options that you can use
Balaji Institute of Technology and Science 91
ITWS Lab Department of Computer Science and Engineering
to carry out commands. To display a toolbar, point to Toolbars on the View
menu. If you don't see the button you want, click the arrows at the right end
of the toolbar.), and then click the color that you want on the palette.
To apply the most recently selected color, click Fill Color .
To fill cells with a pattern, click Cells on the Format menu. On the Patterns
tab, under Cell shading, click the background color that you want to use for
the pattern. Then click the arrow next to the Pattern box, and click the
pattern style and pattern color.
To remove a fill color or fill pattern from selected cells or cell ranges, click the
arrow next to Fill Color , and then click No Fill.
To calculate the Sum
You can add numbers as you type them into a cell. For example, type =5+10 in a
cell to display the result 15.
Add all contiguous numbers in a row or column
You can use AutoSum to do this task.
1. Click a cell below the column of numbers or to the right of the row of numbers.
2. Click AutoSum on the Standard toolbar (toolbar: A bar with buttons and
options that you use to carry out commands. To display a toolbar, click
Customize on the Tools menu, and then click the Toolbars tab.), and then
press ENTER.
Balaji Institute of Technology and Science 92
ITWS Lab Department of Computer Science and Engineering
To Change the Text Orientation
For the optimal display of the data on your worksheet (worksheet: The primary
document that you use in Excel to store and work with data. Also called a
spreadsheet. A worksheet consists of cells that are organized into columns and rows;
a worksheet is always stored in a workbook.), you may want to reposition the text
within a cell. You can change the alignment of the cell contents, use indentation for
better spacing, or display the data at a different angle by rotating it.
1. Select the cell or range (range: Two or more cells on a sheet. The cells in a
range can be adjacent or nonadjacent.) of cells that contains the data that
you want to reposition.
2. On the Format menu, click Cells.
3. On the Alignment tab, do one of the following:
a. To change the horizontal alignment of the cell contents, click the
alignment that you want in the Horizontal box.
To calculate the average
The average is also called the mean.
Calculate the average of numbers in a contiguous row or column
1. Click a cell below or to the right of the numbers for which you want to find the
average.
2. Click the arrow next to AutoSum on the Standard toolbar (toolbar: A bar
with buttons and options that you use to carry out commands. To display a
toolbar, click Customize on the Tools menu, and then click the Toolbars
tab.), and then click Average, and then press ENTER.
Calculate the average of numbers not in a contiguous row or column
Use the AVERAGE function to do this task.
Worksheet example
The example may be easier to understand if you copy it to a blank worksheet.
How?
1. Create a blank workbook or worksheet.
2. Select the example in the Help topic. Do not select the row or column
3.
4. Selecting an example from Help
5. Press CTRL+C.
6. In the worksheet, select cell A1, and press CTRL+V.
Balaji Institute of Technology and Science 93
ITWS Lab Department of Computer Science and Engineering
A
Data
10
7
9
27
0
4
Formula Description (Result)
=AVERAGE(A2:A7) Averages all of numbers in list above (9.5)
=AVERAGE(A2:A4,A7) Averages the top three and the last number in
the list (7.5)
=AVERAGE(IF(A2:A7<>0, Averages the numbers in the list except those
A2:A7,"")) that contain zero, such as cell A6 (11.4)
7. To switch between viewing the results and viewing the formulas that
return the results, press CTRL+ (grave accent), or on the Tools menu,
point to Formula Auditing, and then click Formula Auditing Mode.
Note The last formula in the example must be entered as an array formula (array
formula: A formula that performs multiple calculations on one or more sets of values,
and then returns either a single result or multiple results. Array formulas are
enclosed between braces { } and are entered by pressing CTRL+SHIFT+ENTER.).
After copying the example to a blank worksheet, select the cell A11. Press F2, and
then press CTRL+SHIFT+ENTER. If the formula is not entered as an array formula,
the error #VALUE! is returned.
Function details
AVERAGE
Calculate a weighted average
Use the SUMPRODUCT and SUM functions to do this task.
Worksheet example
The example may be easier to understand if you copy it to a blank worksheet.
How?
1. Create a blank workbook or worksheet.
2. Select the example in the Help topic. Do not select the row or column
Selecting an example from Help
Balaji Institute of Technology and Science 94
ITWS Lab Department of Computer Science and Engineering
3. Press CTRL+C.
A B
Price per unit Number of units
20 500
25 750
35 200
Formula Description (Result)
=SUMPRODUCT(A2:A4,B2:B4)/SUM(B2:B4) Divides the total cost of all three
orders by the total number of units
ordered (24.66)
4. In the worksheet, select cell A1, and press CTRL+V.
5. To switch between viewing the results and viewing the formulas that return
the results, press CTRL+ (grave accent), or on the Tools menu, point to
Formula Auditing, and then click Formula Auditing Mode.
This example calculates the average price paid for a unit across three purchases,
where each purchase is for a different number of units at a different price per unit.
Function details
SUM
SUMPRODUCT
Calculate the average of numbers, ignoring zero (0) values
Use the AVERAGE and IF functions to do this task.
Worksheet example
The example may be easier to understand if you copy it to a blank worksheet.
How?
1. Create a blank workbook or worksheet.
2. Select the example in the Help topic. Do not select the row or column
Selecting an example from Help
3. Press CTRL+C.
Balaji Institute of Technology and Science 95
ITWS Lab Department of Computer Science and Engineering
A
Data
10
7
9
27
0
4
Formula Description (Result)
=AVERAGE(IF(A2:A7<>0, Averages the numbers in the list except those
A2:A7,"")) that contain zero, such as cell A6 (11.4)
4. In the worksheet, select cell A1, and press CTRL+V.
5. To switch between viewing the results and viewing the formulas that return
the results, press CTRL+ (grave accent), or on the Tools menu, point to
Formula Auditing, and then click Formula Auditing Mode.
Function details
AVERAGE
IF
Returns the average (arithmetic mean) of the arguments.
Syntax
AVERAGE(number1,number2,...)
Number1, number2, ... are 1 to 30 numeric arguments for which you want the
average.
Remarks
1. Arguments can either be numbers or names, arrays, or references that
contain numbers.
2. Logical values and text representations of numbers that you type directly into
the list of arguments are counted.
3. If an array or reference argument contains text, logical values, or empty cells,
those values are ignored$$;$$however, cells with the value zero are included.
4. Arguments that are error values or text that cannot be translated into
numbers cause errors.
5. If you want to include logical values and text representations of numbers in a
reference as part of the calculation, use the AVERAGEA function.
To calculate the Standard Deviation
Syntax
STDEV(number1,number2,...)
Number1, number2, ... are 1 to 30 number arguments corresponding to a sample
of a population. You can also use a single array or a reference to an array instead of
arguments separated by commas.
Example
Balaji Institute of Technology and Science 96
ITWS Lab Department of Computer Science and Engineering
Suppose 10 tools stamped from the same machine during a production run are
collected as a random sample and measured for breaking strength.
The example may be easier to understand if you copy it to a blank worksheet.
How?
1. Create a blank workbook or worksheet.
2. Select the example in the Help topic. Do not select the row or column
A Selecti
ng an
Strength
exampl
1345 e from
Help
1301
3.
1368 Press
CTRL+
1322 C.
4.
1310 In the
worksh
1370 eet,
select
1318 cell A1,
and
1350
press
1303 CTRL+
V.
1299 5.
To
Formula Description (Result) switch
betwee
=STDEV(A2:A11) Standard deviation of breaking strength (27.46391572) n
viewin
g the results and viewing the formulas that return the results, press CTRL+
(grave accent), or on the Tools menu, point to Formula Auditing, and then
click Formula Auditing Mode.
Estimates standard deviation based on a sample. The standard deviation is a
measure of how widely values are dispersed from the average value (the mean).
Syntax
STDEVA(value1,value2,...)
Value1, value2, ... are 1 to 30 values corresponding to a sample of a population.
You can also use a single array or a reference to an array instead of arguments
separated by commas.
Remarks
Balaji Institute of Technology and Science 97
ITWS Lab Department of Computer Science and Engineering
1. STDEVA assumes that its arguments are a sample of the population. If your
data represents the entire population, you must compute the standard
deviation using STDEVPA.
2. The standard deviation is calculated using the "unbiased" or "n-1" method.
3. Arguments can be the following: numbers$$;$$names, arrays, or references that
contain numbers$$;$$text representations of numbers$$;$$or logical values, such as
TRUE and FALSE, in a reference.
4. Arguments that contain TRUE evaluate as 1$$;$$arguments that contain text or
FALSE evaluate as 0 (zero).
5. If an argument is an array or reference, only values in that array or reference
are used. Empty cells and text values in the array or reference are ignored.
6. Arguments that are error values or text that cannot be translated into
numbers cause errors.
7. If you do not want to include logical values and text representations of
numbers in a reference as part of the calculation, use the STDEV function.
8. STDEVA uses the following formula:
9.
10. where x is the sample mean AVERAGE(value1,value2,…) and n is the sample
size.
Example
Suppose 10 tools stamped from the same machine during a production run are
collected as a random sample and measured for breaking strength.
The example may be easier to understand if you copy it to a blank worksheet.
How?
1. Create a blank workbook or worksheet.
2. Select the example in the Help topic. Do not select the row or column
Selecting an example from Help
3. Press CTRL+C.
4. In the worksheet, select cell A1, and press CTRL+V.
5. To switch between viewing the results and viewing the formulas that return
the results, press CTRL+ (grave accent), or on the Tools menu, point to
Formula Auditing, and then click Formula Auditing Mode.
To create a Chart
You can quickly create a chart in Microsoft Excel by using the Chart Wizard. In this
wizard, you can choose from a variety of chart types and specify various chart
options. Although worksheet (worksheet: The primary document that you use in
Excel to store and work with data. Also called a spreadsheet. A worksheet consists of
cells that are organized into columns and rows$$;$$a worksheet is always stored in a
Balaji Institute of Technology and Science 98
ITWS Lab Department of Computer Science and Engineering
workbook.) data that you want to plot in a chart can be located in rows or columns,
some chart types require a specific arrangement of the data before you can create a
1. On the worksheet, arrange the data that you want to plot in a chart.
How to arrange data for different chart types
o For a column, bar, line, area, surface or radar chart, you should
arrange the data in columns or rows.
Data in columns:
Lorem Ipsum
1 2
3 4
Data in rows:
Lorem 1 3
Ipsum 2 4
o For a pie or doughnut chart with only one series of data, you should
arrange the data in one column or row only.
One column of data and one column of data labels:
A 1
B 2
C 3
One row of data and one row of data labels:
A B C
1 2 3
o For a pie chart or doughnut chart that has more than one series of
data, you can arrange the data in more than one column or row.
More than one column of data:
A 1 2
B 3 4
C 5 6
More than one row of data:
A B C
1 2 3
4 5 6
o For an xy (scatter) or bubble chart, you can arrange the data in
columns, so that x values are listed in the first column and
Balaji Institute of Technology and Science 99
ITWS Lab Department of Computer Science and Engineering
corresponding y values and/or bubble size values are listed in adjacent
columns.
Data in columns:
X Y Bubble
1 2 3
4 5 6
o For a stock chart, you need to arrange data in the following order (in
rows or columns): high values, low values, and closing values. Use
names or dates as labels.
Data in columns:
Date High Low Close
1/1/2002 46.125 42 44.063
2. Select the cells that contain the data that you want to use for the chart.
3. Tip If the cells that you want to select for the chart are not in a continuous
range, select the first group of cells that contain the data that you want to
include. Hold down CTRL, and then select any additional cell groups that you
want to include. The nonadjacent selections must form a rectangle.
4.
5. Click Chart Wizard on the Standard toolbar, or click Chart on the
6. Follow the instructions in the Chart Wizard.
7. For information about the Chart Wizard options, click Help in the title bar
of the wizard.
Tips
To quickly create a basic chart that is displayed on a separate chart
sheet (chart sheet: A sheet in a workbook that contains only a chart. A chart sheet
is beneficial when you want to view a chart or a PivotChart report separately from
worksheet data or a PivotTable report.), select the data that you want to use for the
chart, and then press ALT+F1 or F11.
If you use a specific chart type frequently when you create a chart, you may
want to set that chart type as the default chart type.
Change the default chart type
1. Click anywhere in the chart area (chart area: The entire chart and all its
elements.) to select the chart.
2. On the Chart menu, click Chart Type.
3. On the Standard Types tab or Custom Types tab, in the Chart type list,
click the chart type that you want or accept the current selection, and then
click Set As Default Chart.
4. Click Yes, and then click OK.
Balaji Institute of Technology and Science 100
ITWS Lab Department of Computer Science and Engineering
5. If the Add Custom Chart Type dialog box appears, type a name in the
Name box and a description in the Description box, and then click OK.
Notes
1. When you create a chart, the Chart toolbar is displayed and the Chart menu
commands to modify the chart. For example, use the toolbar to select specific
items in the chart, change the chart type, make formatting changes, show or
hide the legend or data table, or switch between displaying the data series by
row and displaying it by column. The Chart menu allows you to make
changes to the source data, add data to the chart, specify numerous chart
options, change the location of the chart, and apply 3-D effects. The Chart
menu does not, however, provide a command for creating a chart.
2. The Chart toolbar can also be displayed (or hidden) at any time by pointing
to Toolbars on the View menu, and then clicking Chart. If you display the
Chart toolbar before you create a chart, you can use it to create a chart.
Select the cells that contain the data that you want to use in the chart, and
then click Chart Type on the Chart toolbar. The chart will be displayed in the
selected chart type on the same worksheet.
This is also called a 3-D reference (3-D reference: A reference to a range that spans
two or more worksheets in a workbook.).
1. On the Insert menu, point to Name, and then click Define.
2. In the Names in workbook box, type the name.
3. If the Refers to box contains a reference, select the equal sign (=) and the
reference and press BACKSPACE.
4. In the Refers to box, type = (equal sign).
5. Click the tab for the first worksheet to be referenced.
6. Hold down SHIFT and click the tab for the last worksheet to be referenced.
7. Select the cell or range of cells to be referenced.
A reference identifies a cell or a range of cells on a worksheet and tells Microsoft
Excel where to look for the values or data you want to use in a formula. With
references, you can use data contained in different parts of a worksheet in one
formula or use the value from one cell in several formulas. You can also refer to cells
on other sheets in the same workbook, and to other workbooks. References to cells
in other workbooks are called links.
The A1 reference style
By default, Excel uses the A1 reference style, which refers to columns with letters (A
through IV, for a total of 256 columns) and refers to rows with numbers (1 through
65536). These letters and numbers are called row and column headings. To refer to
a cell, enter the column letter followed by the row number. For example, B2 refers to
the cell at the intersection of column B and row 2.
To refer to Use
The cell in column A and row 10 A10
The range of cells in column A and rows 10 through 20 A10:A20
The range of cells in row 15 and columns B through E B15:E15
All cells in row 5 5:5
Balaji Institute of Technology and Science 101
ITWS Lab Department of Computer Science and Engineering
All cells in rows 5 through 10 5:10
All cells in column H H:H
All cells in columns H through J H:J
The range of cells in columns A through E and rows 10 through 20 A10:E20
Reference to another worksheet In the following example, the AVERAGE
worksheet function calculates the average value for the range B1:B10 on the
worksheet named Marketing in the same workbook.
Link to another worksheet in the same workbook
Note that the name of the worksheet and an exclamation point (!) precede the range
reference.
The difference between relative and absolute references
Relative references A relative cell reference in a formula, such as A1, is based on
the relative position of the cell that contains the formula and the cell the reference
refers to. If the position of the cell that contains the formula changes, the reference
is changed. If you copy the formula across rows or down columns, the reference
automatically adjusts. By default, new formulas use relative references. For example,
if you copy a relative reference in cell B2 to cell B3, it automatically adjusts from
=A1 to =A2.
Copied formula with relative reference
Absolute references An absolute cell reference in a formula, such as $A$1,
always refer to a cell in a specific location. If the position of the cell that contains the
formula changes, the absolute reference remains the same. If you copy the formula
across rows or down columns, the absolute reference does not adjust. By default,
new formulas use relative references, and you need to switch them to absolute
references. For example, if you copy a absolute reference in cell B2 to cell B3, it
stays the same in both cells =$A$1.
Copied formula with absolute reference
Mixed references A mixed reference has either an absolute column and relative
row, or absolute row and relative column. An absolute column reference takes the
form $A1,$B1, and so on. An absolute row reference takes the form A$1, B$1, and
so on. If the position of the cell that contains the formula changes, the relative
reference is changed, and the absolute reference does not change. If you copy the
formula across rows or down columns, the relative reference automatically adjusts,
Balaji Institute of Technology and Science 102
ITWS Lab Department of Computer Science and Engineering
and the absolute reference does not adjust. For example, if you copy a mixed
reference from cell A2 to B3, it adjusts from =A$1 to =B$1.
Copied formula with mixed reference
The 3-D reference style
If you want to analyze data in the same cell or range of cells on multiple worksheets
within the workbook, use a 3-D reference. A 3-D reference includes the cell or range
reference, preceded by a range of worksheet names. Excel uses any worksheets
stored between the starting and ending names of the reference. For example,
=SUM(Sheet2:Sheet13!B5) adds all the values contained in cell B5 on all the
worksheets between and including Sheet 2 and Sheet 13.
You can use 3-D references to refer to cells on other sheets, to define
names, and to create formulas by using the following functions: SUM, AVERAGE,
AVERAGEA, COUNT, COUNTA, MAX, MAXA, MIN, MINA, PRODUCT, STDEV, STDEVA,
STDEVP, STDEVPA, VAR, VARA, VARP, and VARPA.
3-D references cannot be used in array formulas (array formula: A formula
that performs multiple calculations on one or more sets of values, and then returns
either a single result or multiple results. Array formulas are enclosed between
braces { } and are entered by pressing CTRL+SHIFT+ENTER.).
3-D references cannot be used with the intersection operator (operator: A
sign or symbol that specifies the type of calculation to perform within an
expression. There are mathematical, comparison, logical, and reference operators.)
(a single space) or in formulas that use implicit intersection (implicit intersection: A
reference to a range of cells, instead of a single cell, that is calculated like a single
cell. If cell C10 contains the formula =B5:B15*5, Excel multiplies the value in cell
B10 by 5 because cells B10 and C10 are in the same row.).
How 3-D references change when you move, copy, insert, or delete
worksheets
The following examples explain what happens when you move, copy, insert, or
delete worksheets that are included in a 3-D reference. The examples use the
formula =SUM(Sheet2:Sheet6!A2:A5) to add cells A2 through A5 on worksheets 2
through 6.
Insert or copy If you insert or copy sheets between Sheet2 and Sheet6 (the
endpoints in this example), Microsoft Excel includes all values in cells A2 through A5
from the added sheets in the calculations.
Delete If you delete sheets between Sheet2 and Sheet6, Excel removes their
values from the calculation.
Move If you move sheets from between Sheet2 and Sheet6 to a location outside
the referenced sheet range, Excel removes their values from the calculation.
Move an endpoint If you move Sheet2 or Sheet6 to another location in the same
workbook, Excel adjusts the calculation to accommodate the new range of sheets
between them.
Delete an endpoint If you delete Sheet2 or Sheet6, Excel adjusts the calculation
to accommodate the range of sheets between them.
Objective:
a. How to use nested functions?
Balaji Institute of Technology and Science 103
ITWS Lab Department of Computer Science and Engineering
b. What are the logical operators and how can I use them for manipulating data?
by implementing a Capital gains and loss worksheet.
Description:
This task requires you to implement and learn how to
1. To create Nested functions
2. To make use of logical operators
Step By Step Guide:
To use Nested Functions
In certain cases, you may need to use a function as one of the
arguments (argument: The values that a function uses to perform operations or
calculations. The type of argument a function uses is specific to the function.
Common arguments that are used within functions include numbers, text, cell
references, and names.) of another function. For example, the following formula uses
a nested AVERAGE function and compares the result with the value 50.
Valid returns When a nested function is used as an argument, it must return the
same type of value that the argument uses. For example, if the argument returns a
TRUE or FALSE value, then the nested function must return a TRUE or FALSE. If it
doesn't, Microsoft Excel displays a #VALUE! error value.
Nesting level limits A formula can contain up to seven levels of nested functions.
When Function B is used as an argument in Function A, Function B is a second-level
function. For instance, the AVERAGE function and the SUM function are both second-
level functions because they are arguments of the IF function. A function nested
within the AVERAGE function would be a third-level function, and so on
To use Nested Functions
You can use the AND, OR, NOT, and IF function to create conditional formulas. The
IF function uses the following arguments.
Formula with the IF function
logical_test: the condition you want to check
value_if_true: the value to return if the condition is true
value_if_false: the value to return if the condition is false
Balaji Institute of Technology and Science 104
ITWS Lab Department of Computer Science and Engineering
A
Data
15
9
8
Sprockets
Widgets
Formula Description (Result)
=AND(A2>A3, A2<A4) Is 15 greater than 9 and less than 8? (FALSE)
=OR(A2>A3, A2<A4) Is 15 greater than 9 or less than 8? (TRUE)
=NOT(A2+A3=24) Is 15 plus 9 not equal to 24? (FALSE)
=NOT(A5="Sprockets") Is A5 not equal to "Sprockets"? (FALSE)
=OR(A5<>"Sprockets",A6 = Is A5 not equal to "Sprockets" or A6 equal to
"Widgets") "Widgets"? (TRUE)
A
Data
15
9
8
Sprockets
Widgets
Formula Description (Result)
=IF(A2=15, "OK", "Not If the value in cell A2 equals 15, then return "OK".
OK") (OK)
=IF(A2<>15, "OK", "Not If the value in cell A2 is not equal to 15, then return
OK") "OK". (Not OK)
Create a conditional formula that results in a logical value (TRUE or FALSE)
Use the AND, OR, and NOT functions, and operators (operator: A sign or symbol that
specifies the type of calculation to perform within an expression. There are
mathematical, comparison, logical, and reference operators.) to do this task, as
presented in the following example worksheet.
Balaji Institute of Technology and Science 105
ITWS Lab Department of Computer Science and Engineering
The example may be easier to understand if you copy it to a blank worksheet.
How?
1. Create a blank workbook or worksheet.
2. Select the example in the Help topic. Do not select the row or column
Selecting an example from Help
3. Press CTRL+C.
4. In the worksheet, select cell A1, and press CTRL+V.
5. To switch between viewing the results and viewing the formulas that return
the results, press CTRL+ (grave accent), or on the Tools menu, point to Formula
Auditing, and then click Formula Auditing Mode.
Create a conditional formula that results in another calculation, or values other
than TRUE or FALSE
Use the IF, AND, and OR functions to do this task, as presented in the following
example worksheet.
Balaji Institute of Technology and Science 106
ITWS Lab Department of Computer Science and Engineering
To calculate the NPV (Net Present Value)
Calculates the net present value of an investment by using a discount rate and a
series of future payments (negative values) and income (positive values).
Syntax
NPV(rate,value1,value2, ...)
Rate is the rate of discount over the length of one period.
Value1, value2, ... are 1 to 29 arguments representing the payments and
income.
1. Value1, value2, ... must be equally spaced in time and occur at the end of
each period.
2. NPV uses the order of value1, value2, ... to interpret the order of cash flows.
Be sure to enter your payment and income values in the correct sequence.
3. Arguments that are numbers, empty cells, logical values, or text
representations of numbers are counted$$;$$arguments that are error values or
text that cannot be translated into numbers are ignored.
4. If an argument is an array or reference, only numbers in that array or
reference are counted. Empty cells, logical values, text, or error values in the
array or reference are ignored.
Remarks
1. The NPV investment begins one period before the date of the value1 cash flow
and ends with the last cash flow in the list. The NPV calculation is based on
future cash flows. If your first cash flow occurs at the beginning of the first
period, the first value must be added to the NPV result, not included in the
2. If n is the number of cash flows in the list of values, the formula for NPV is:
3.
4. NPV is similar to the PV function (present value). The primary difference
between PV and NPV is that PV allows cash flows to begin either at the end or
at the beginning of the period. Unlike the variable NPV cash flow values, PV
cash flows must be constant throughout the investment. For information
about annuities and financial functions, see PV.
5. NPV is also related to the IRR function (internal rate of return). IRR is the rate
for which NPV equals zero: NPV(IRR(...), ...) = 0.
To make use of the Split panes
1. At the top of the vertical scroll bar or at the right end of the horizontal scroll
bar, point to the split box.
2. When the pointer changes to a split pointer, drag the split box down or to the
left to the position you want.
Balaji Institute of Technology and Science 107
ITWS Lab Department of Computer Science and Engineering
To create a new Worksheets
1. Click Worksheet on the Insert menu.
Determine the number or worksheets you want to add.
1. Hold down SHIFT, and then select the same number of existing worksheet tabs
that you want to add in the open workbook.
2. Example: If you want to add three new worksheets, select three existing
worksheet tabs.
3. Click Worksheet on the Insert menu.
Insert a new sheet that's based on a custom template
You must have already created a custom sheet template.
How?
1. Decide which type of template you want:
Workbook template
Create a workbook that contains the sheets, default text (such as page headers
and column and row labels), formulas, macros (macro: An action or a set of
actions you can use to automate tasks. Macros are recorded in the Visual Basic
for Applications programming language.), styles (style: A combination of
formatting characteristics, such as font, font size, and indentation, that you name
and store as a set. When you apply a style, all of the formatting instructions in
that style are applied at one time.), and other formatting you want in new
workbooks based on the template.
Worksheet template
Create a workbook that contains one worksheet. On the worksheet, include the
formatting, styles (style: A combination of formatting characteristics, such as
font, font size, and indentation, that you name and store as a set. When you
apply a style, all of the formatting instructions in that style are applied at one
time.), text, and other information you want to appear on all new sheets of the
same type.
2. To display a picture of the first page of a template in the Preview box of the
Templates dialog box (General Templates..., New Workbook task pane),
click Properties on the File menu, click the Summary tab, and then select the
Save preview picture check box.
3. On the File menu, click Save As.
4. In the Save as type box, click Template.
Balaji Institute of Technology and Science 108
ITWS Lab Department of Computer Science and Engineering
5. In the Save in box, select the folder where you want to store the template.
1. To create the default workbook template (default workbook template: The
Book.xlt template that you create to change the default format of new
workbooks. Excel uses the template to create a blank workbook when you
start Excel or create a new workbook without specifying a template.) or
default worksheet template (default worksheet template: The Sheet.xlt
template that you create to change the default format of new worksheets.
Excel uses the template to create a blank worksheet when you add a new
worksheet to a workbook.), select either the XLStart folder or the
alternate startup folder (alternate startup folder: A folder in addition to
the XLStart folder that contains workbooks or other files that you want to
be opened automatically when you start Excel and templates that you
want to be available when you create new workbooks.). The XLStart folder
is usually
C:\Program Files\Microsoft Office\Office11\XLStart
2. To create a custom workbook or worksheet template, select the
Templates folder, which is usually
C:\Documents and Settings\user_name\Application
Data\Microsoft\Templates
6. Enter the name of the template in the File name box. Do one of the following:
Workbook template
1. Type book to create the default workbook template.
2. To create a custom workbook template, type any valid file name.
Worksheet template
1. Type sheet to create a template for default worksheets.
2. To create a custom sheet template, type any valid file name.
7. Click Save, and then click Close on the File menu.
To insert a new worksheet
1. Right-click a sheet tab, and then click Insert.
2. Double-click the template for the type of sheet you want.
The name (or title) of a worksheet (worksheet: The primary document that you use
in Excel to store and work with data. Also called a spreadsheet. A worksheet consists
of cells that are organized into columns and rows$$;$$a worksheet is always stored in a
workbook.) appears on its sheet tab on the Sheet tab bar at the bottom of the
screen. By default, the name is Sheet1, Sheet2, and so on, but you can give your
worksheet a more appropriate name.
1. To rename the active sheet, do one of the following:
On the Format menu, point to Sheet and then click Rename.
On the Sheet tab bar, right-click the tab you want to rename, and
then click Rename.
2. Type the new name over the current name.
Tip You can include the name of the sheet when you print the worksheet. On the
View menu, click Header and Footer, and then, in the Page Setup dialog box on
the Header/Footer tab, click Custom Header or Custom Footer. In the Left
Balaji Institute of Technology and Science 109
ITWS Lab Department of Computer Science and Engineering
section, Center section, or Right section box, enter the sheet tab by clicking Tab
in the row of buttons in the Header or Footer dialog box.
To create a hyperlink to a specific location in a workbook
To link to a location in the current workbook or another workbook, you can either
define a name (name: A word or string of characters that represents a cell, range of
cells, formula, or constant value. Use easy-to-understand names, such as Products,
to refer to hard to understand ranges, such as Sales!C20:C30.) for the
destination (destination: General term for the name of the element you go to from a
hyperlink.) cells or use a cell reference.
1. To use a name, name the destination cells in the destination workbook.
How?
selection: A selection of two or more cells or ranges that don't touch each
other. When plotting nonadjacent selections in a chart, make sure that the
combined selections form a rectangular shape.) that you want to name.
2. Click the Name box at the left end of the formula bar (formula bar: A bar at
the top of the Excel window that you use to enter or edit values or formulas in
cells or charts. Displays the constant value or formula stored in the active
cell.) .
Name box
3. Type the name for the cells.
4. Press ENTER.
Note You cannot name a cell while you are changing the contents of the cell.
2. In the source (source file: The file that contains information that was used to
create a linked or embedded object. When you update the information in the
source file, you can also update the linked object in the destination file.)
workbook, right-click the text or graphic you want to represent the
hyperlink (hyperlink: Colored and underlined text or a graphic that you click to go
to a file, a location in a file, a Web page on the World Wide Web, or a Web page
on an intranet. Hyperlinks can also go to newsgroups and to Gopher, Telnet, and
3. Do one of the following:
1. To link to a location in your current workbook, click Place in this
2. To link to a location in another workbook, click Existing file or Web
4. If you chose Existing file or Web page, locate and select the workbook you
want to link to, and then click the Bookmark button.
5. Do one of the following:
1. In the list under Cell Reference, click the sheet you want to link to,
and then type the cell reference in the Type in the cell reference
box. Click OK.
2. In the list under Defined Names, click the name that represents the
cells you want to link to. Click OK.
6. To assign a tip to be displayed when you rest the pointer on the hyperlink, click
ScreenTip and then type the text you want in the ScreenTip text box. Click
OK.
Balaji Institute of Technology and Science 110
ITWS Lab Department of Computer Science and Engineering
To use HLookup and VLookup functions
We use HLookup and VLookup to find records in large worksheets, explained the
basics of using the HLOOKUP and VLOOKUP functions in Microsoft Excel to find
records in a large worksheet. This column explains several other ways to use those
functions.
Use relative and absolute cell references to return multiple results
The instance of VLOOKUP that you created in the previous section contains a
reference to Cell F3. Excel calls that type of reference a relative reference, meaning
that if you copy the formula down or across a range of cells, Excel automatically
increases the cell reference by 1 for each new instance of the formula. If any of
those instances of the formula reference empty cells, Excel displays the #N/A error.
In contrast, absolute cell references do not change when you copy them down or
across a range of cells, so using them can help you avoid #N/A errors. The following
steps demonstrate how relative cell references can cause #N/A errors, and how
absolute references can fix them.
1. On the Page Views worksheet, copy and paste or type this formula into Cell D4:
=VLOOKUP(A4,Pages!A2:B39,2,false)
2. Click Cell D4, rest your mouse pointer on the lower-right corner of the cell until it
changes to a black plus sign (+), and then drag the mouse pointer down to Cell
D41. The page names that correspond to each ID appear in Column D.
At this point, #N/A appears in several cells. What happened? If you click cells in
Column D, you see that Excel also increased the cell references by one after the
word Pages! in the formula. (In case you haven't read the previous article,
the argument, read the previous article.) In other words, the formula in Cell D4
references Cells A2 through B39 on the Pages worksheet, which is what you want.
But look at the formula associated with Cell D5: It references Cells A3 through B40.
If you go back to the Pages worksheet, you'll see that Cell B40 is empty. Excel
returns the #N/A message because some instances of the formula contain references
to empty cells.
To work around the problem, use absolute cell references. Absolute references
prevent Excel from changing cell references in a formula when you copy that
1. In the Page Views worksheet, clear Cells D5 through D41.
2. In Cell D4 (or the formula bar, if that's easier), add dollar signs to the formula as
shown:
=VLOOKUP(A4,Pages!$A$2:$B$39,2,FALSE)
The dollar signs make the cell references absolute.
3. Point to the lower-right corner of Cell D4 until your mouse pointer changes to a
black plus sign, and then drag the pointer down to Cell D41. As you copy the
formula, the dollar signs prevent Excel from changing any cell references in the
table array argument. This time, the page names that correspond to each ID
appear in Column D with no errors.
The formula in Step 2 uses absolute columns and rows (the dollar signs are a dead
giveaway). You can use a mix of relative columns and absolute rows, or vice versa.
For example:
Balaji Institute of Technology and Science 111
ITWS Lab Department of Computer Science and Engineering
1. If you need a relative column reference and an absolute row reference,
use A$2. 2. If you need an absolute column reference and a relative row reference, use$A2.
You can mix absolute and relative references as needed. For example, you could use
$A2:B$39, or any other combination of characters. Just make sure that you place the
dollar sign before the column or row that you want to designate as an absolute
reference. The function fails otherwise.
error, Correct a #REF! error, and Correct a #VALUE! error.
Use formula auditing to find empty cells and fix broken functions
Typically, a function doesn't work because it references at least one empty cell. You
can use the formula auditing tools in Excel to find the empty cell and fix the broken
function. The formula auditing tools use arrows and icons to point to the cells from
which a function tries to take the data it needs.
Important To follow the steps in this section, you must first enable an error
checking option. On the Tools menu, click Options, click the Error Checking tab,
and then select the Formulas referring to empty cells check box.
To see the auditing tools in action:
1. On the Page Views worksheet, remove the dollar signs from the formula in cell
D4.
2. Clear cells D5 through D41, and then copy the changed formula down to Cell
D41. Because all instances of the formula except the first one contain an error,
Excel displays a green triangle in the upper-left corner of each cell:
3. Select Cell D5. The Trace Error icon appears.
4. Click the arrow to the right of the icon, and then click Trace Empty Cell. The
following arrow and icon appear, indicating that the empty cell resides on another
worksheet.
5. Double-click the black arrow that leads from the icon to the cell.
6. Double-click the entry in the Go to dialog box. Excel opens the Pages worksheet
because that worksheet contains the empty cell.
At this point, you need to notice something subtle: In the Pages worksheet, Excel
highlights the cell range A3 to B40, even though the data only resides in cells A2 to
B39. The highlight is showing you that the formula is searching the wrong range of
cells. Hence, the error.
To see a more pronounced example of this behavior, go back to the Page Views
worksheet, select Cell D10, and repeat Steps 4 through 6. The highlight in the Pages
worksheet extends even further down to indicate the greater number of empty cells
referenced by the instance of the formula in Cell D10.
Balaji Institute of Technology and Science 112
ITWS Lab Department of Computer Science and Engineering
Use the Lookup Wizard to save time
If you don't have the time to write a function or if writing functions still frustrates
you, you can use the Lookup Wizard. The Lookup Wizard comes with Excel, so you
don't need to download it (but Excel may prompt you to install it the first time you
try to use it). The wizard uses the INDEX and MATCH functions (instead of VLOOKUP
and HLOOKUP) to return records.
Unlike the lookup functions, the INDEX function requires you to specify row and
column labels. The INDEX function also returns values from unsorted lists.
The MATCH function determines the row that contains the desired value. You can use
INDEX and MATCH to enter more than one search term and return the value that
corresponds to the intersection of the two terms. For example, the following table
contains shipping data for the first three months of 1994, 1995, and 1996.
Units
Shipped
January February March
1994 37 43 61
1995 40 60 52
1996 31 50 64
Using INDEX and MATCH, you can specify multiple search terms such as "1995" and
"March." In that case, the functions would return 52, the value at the intersection of
those terms.
The steps in this section explain how to configure Excel to run the Lookup Wizard,
and how to use the wizard.
First, let's configure Excel.
2. In the Add-Ins dialog box, click Lookup Wizard, and then click OK.
Now let's run the add-in. These steps explain how to duplicate the results you
created earlier using the VLOOKUP function. We'll use values from the Page Views
and Pages worksheets, and return a result to a blank cell on the Page Views
worksheet.
1. Open the sample spreadsheet (LookupFunctions.xls) and select the Pages
worksheet.
Balaji Institute of Technology and Science 113
ITWS Lab Department of Computer Science and Engineering
2. On the Tools menu, click Lookup. You should see the following text and cell
range in the wizard.
If the text seems a bit cryptic, remember that you're defining the location and
range of cells through which the function searches. When you see those values,
click Next.
3. Ensure that Page Name appears in the top drop-down box, and then pick a
page ID number from the bottom drop-down box and click Next.
4. Do one of the following:
1. If you want your worksheet to display only the result of your search,
click Copy just the formula to a single cell.
2. If you want the worksheet to display the search result and the
parameters used in the search, click Copy the formula and lookup
parameters, and then click Next.
5. Do one of the following:
1. If you chose to display only the search result, enter a reference to a
blank cell in the box, and then click Finish.
2. If you chose to display the result and the lookup parameters, enter
references to three blank cells, and then click Finish.
The wizard performs the lookup and writes the result or results to the cell or cells
you referenced in Step 6.
A final reminder
As you use lookup functions, remember that you're pointing to a data string in one
location, telling Excel to find either a partial or absolute match for that data string in
another location, and then telling Excel to display a third value that lies either next
to or near that second value.
HLookup
Searches for a value in the top row of a table or an array (array: Used to build single
formulas that produce multiple results or that operate on a group of arguments that
are arranged in rows and columns. An array range shares a common formula$$;$$an
array constant is a group of constants used as an argument.) of values, and then
returns a value in the same column from a row you specify in the table or array. Use
HLOOKUP when your comparison values are located in a row across the top of a
table of data, and you want to look down a specified number of rows. Use VLOOKUP
when your comparison values are located in a column to the left of the data you
want to find.
The H in HLOOKUP stands for "Horizontal."
Syntax
HLOOKUP(lookup_value,table_array,row_index_num,range_lookup)
Lookup_value is the value to be found in the first row of the table. Lookup_value
can be a value, a reference, or a text string.
Table_array is a table of information in which data is looked up. Use a reference
to a range or a range name.
Balaji Institute of Technology and Science 114
ITWS Lab Department of Computer Science and Engineering
1. The values in the first row of table_array can be text, numbers, or logical
values.
2. If range_lookup is TRUE, the values in the first row of table_array must be
placed in ascending order: ...-2, -1, 0, 1, 2,... , A-Z, FALSE, TRUE$$;$$otherwise,
HLOOKUP may not give the correct value. If range_lookup is FALSE,
table_array does not need to be sorted.
3. Uppercase and lowercase text are equivalent.
4. You can put values in ascending order, left to right, by selecting the values
and then clicking Sort on the Data menu. Click Options, click Sort left to
right, and then click OK. Under Sort by, click the row in the list, and then
click Ascending.
Row_index_num is the row number in table_array from which the matching value
will be returned. A row_index_num of 1 returns the first row value in table_array, a
row_index_num of 2 returns the second row value in table_array, and so on. If
row_index_num is less than 1, HLOOKUP returns the #VALUE! error value$$;$$if
row_index_num is greater than the number of rows on table_array, HLOOKUP
returns the #REF! error value.
Range_lookup is a logical value that specifies whether you want HLOOKUP to find
an exact match or an approximate match. If TRUE or omitted, an approximate match
is returned. In other words, if an exact match is not found, the next largest value
that is less than lookup_value is returned. If FALSE, HLOOKUP will find an exact
match. If one is not found, the error value #N/A is returned.
Remarks
1. If HLOOKUP can't find lookup_value, and range_lookup is TRUE, it uses the
largest value that is less than lookup_value.
2. If lookup_value is smaller than the smallest value in the first row of
table_array, HLOOKUP returns the #N/A error value.
3. If range_lookup is FALSE and lookup_value is text, you can use the wildcard
characters, question mark (?) and asterisk (*), in lookup_value. A question
mark matches any single character$$;$$an asterisk matches any sequence of
characters. If you want to find an actual question mark or asterisk, type a
tilde (~) before the character.
VLOOKUP
Searches for a value in the first column of a table array and returns a value in the
same row from another column in the table array.
The V in VLOOKUP stands for vertical. Use VLOOKUP instead of HLOOKUP when
your comparison values are located in a column to the left of the data that you want
to find.
Syntax
VLOOKUP(lookup_value,table_array,col_index_num,range_lookup)
Lookup_value The value to search in the first column of the table array (array:
Used to build single formulas that produce multiple results or that operate on a
group of arguments that are arranged in rows and columns. An array range shares a
common formula$$;$$an array constant is a group of constants used as an argument.).
Lookup_value can be a value or a reference. If lookup_value is smaller than the
smallest value in the first column of table_array, VLOOKUP returns the #N/A error
value.
Table_array Two or more columns of data. Use a reference to a range or a range
name. The values in the first column of table_array are the values searched by
Balaji Institute of Technology and Science 115
ITWS Lab Department of Computer Science and Engineering
lookup_value. These values can be text, numbers, or logical values. Uppercase and
lowercase text are equivalent.
Col_index_num The column number in table_array from which the matching value
must be returned. A col_index_num of 1 returns the value in the first column in
table_array$$;$$a col_index_num of 2 returns the value in the second column in
table_array, and so on. If col_index_num is:
Less than 1, VLOOKUP returns the #VALUE! error value.
Greater than the number of columns in table_array, VLOOKUP returns the
#REF! error value.
Range_lookup A logical value that specifies whether you want VLOOKUP to find an
exact match or an approximate match:
If TRUE or omitted, an exact or approximate match is returned. If an exact
match is not found, the next largest value that is less than lookup_value is
returned.
The values in the first column of table_array must be placed in ascending sort
order$$;$$otherwise, VLOOKUP may not give the correct value. You can put the values
in ascending order by choosing the Sort command from the Data menu and
If FALSE, VLOOKUP will only find an exact match. In this case, the values in
the first column of table_array do not need to be sorted. If there are two or more
values in the first column of table_array that match the lookup_value, the first
value found is used. If an exact match is not found, the error value #N/A is
returned.
To make use of the COUNT Function
Counts the number of cells that contain numbers and counts numbers within the list
of arguments. Use COUNT to get the number of entries in a number field that is in a
range or array of numbers.
Syntax
COUNT(value1,value2,...)
Value1, value2, ... are 1 to 30 arguments that can contain or refer to a variety of
different types of data, but only numbers are counted.
Remarks
Arguments that are numbers, dates, or text representation of numbers are
counted.
Logical values and text representations of numbers that you type directly into
the list of arguments are counted.
Arguments that are error values or text that cannot be translated into
numbers are ignored.
If an argument is an array or reference, only numbers in that array or
reference are counted. Empty cells, logical values, text, or error values in the
array or reference are ignored.
If you want to count logical values, text, or error values, use the COUNTA
function.
Balaji Institute of Technology and Science 116
ITWS Lab Department of Computer Science and Engineering
To make use of the Group and Outline option
Create an Outline
This outline lets you show and hide the detail rows for monthly sales.
1. If your summary rows are above the detail rows, or your summary columns
are to the left of the detail columns, change the direction setting.
How?
1. On the Data menu, point to Group and Outline, and then click
Settings.
2. Clear the Summary rows below detail check box, the Summary
columns to right of detail check box, or both check boxes.
2. If you want to set outline styles (style: A combination of formatting
characteristics, such as font, font size, and indentation, that you name and
store as a set. When you apply a style, all of the formatting instructions in
that style are applied at one time.) that will be applied automatically when
the outline is created, set the Automatic styles option.
How?
1. On the Data menu, point to Group and Outline, and then click
Settings.
2. Select the Automatic styles check box.
Note If you don't want to apply automatic styles before you begin, you can
apply them after you create the outline.
3. Decide whether to outline the worksheet automatically or manually.
o You can outline any worksheet manually.
o You can outline worksheets automatically if they have summary
formulas that reference cells in the detail data (detail data: For
automatic subtotals and worksheet outlines, the subtotal rows or
columns that are totaled by summary data. Detail data is typically
adjacent to and either above or to the left of the summary data.). All
columns containing summary formulas must be either to the right or to
the left of the detail data, or rows containing summary formulas must
be either below or above the detail data.
If you aren't sure whether your worksheet meets these requirements,
try outlining automatically, and if the results aren't as you expect,
undo the operation and outline manually instead.
4. Do one of the following:
Outline the data automatically
1. Select the range of cells you want to outline.
To outline the entire worksheet, click any cell on the worksheet.
1. On the Data menu, point to Group and Outline, and then click Auto
Outline.
Outline the data manually
2. Select the rows or columns that contain detail data.
Balaji Institute of Technology and Science 117
ITWS Lab Department of Computer Science and Engineering
Detail rows or columns are usually adjacent to the row or column that
contains the summary formula or a heading. For example, if row 6
contains totals for rows 3 through 5, select rows 3 through 5. If row 8
contains a heading that describes rows 9 through 12, select rows 9
through 12.
3. On the Data menu, point to Group and Outline, and then click
Group.
The outline symbols (outline symbols: Symbols that you use to change
the view of an outlined worksheet. You can show or hide detailed data
by pressing the plus sign, minus sign, and the numbers 1, 2, 3, or 4,
indicating the outline level.) appear beside the group on the screen.
4. Continue selecting and grouping detail rows or columns until you have
created all of the levels you want in the outline.
5. If you didn't select automatic styles, you can apply styles now.
How?
1. Select the cells that you want to apply outline styles to.
2. On the Data menu, point to Group and Outline, and then click
Settings.
3. Select the Automatic styles check box.
4. Click Apply Styles.
Remove an Outline
No data is deleted when you remove an outline.
1. Click the worksheet.
2. On the Data menu, point to Group and Outline, and then click Clear
Outline.
3. If rows or columns are still hidden, drag across the visible row or column
headings on both sides of the hidden rows and columns, point to Row or
Column on the Format menu, and then click Unhide.
To calculate subtotals and totals using grouping and outline
You can have Excel calculate subtotals or totals for portions of your worksheet data.
For example, in a worksheet with sales data for three different product categories,
you can first sort the products by category, and then select all the cells that contain
data and open the Subtotal dialog box (Data menu, Subtotals command).
In the Subtotal dialog box, you can choose the column on which to base your
subtotals (such as every change of value in the Week column), the summary
calculation that you want to perform, and the column or columns with values to be
summarized. For example (as shown in the previous picture), you could calculate
Balaji Institute of Technology and Science 118
ITWS Lab Department of Computer Science and Engineering
subtotals for the number of units sold in each category. After you define your
subtotals, they appear in your worksheet.
As the previous picture shows, when you add subtotals to a worksheet, Excel also
defines groups based on the rows used to calculate the subtotals. The groupings
form an outline of your worksheet based on the criteria that you used to create the
subtotals. All the rows with furniture products are in one group, rows with tools are
in another, and so on. The outline section at the left of the worksheet holds controls
that you can use to hide or display groups of rows.
There are three types of controls in the outline section:
Hide detail buttons When the rows in a group are visible, a hide detail
button appears next to the group.
Show detail buttons When you hide a group of rows, the button next to the
group changes to a show detail button . Clicking a show detail button
restores the rows in that group to the worksheet.
Level buttons Each of the numbered level buttons represents a level of
organization in a worksheet$$;$$clicking a level button hides all levels of detail
below that of the button you clicked.
Balaji Institute of Technology and Science 119
ITWS Lab Department of Computer Science and Engineering
The following table identifies the three levels of organization in the previous graphic.
Level Description
1 The grand total
2 Subtotals for each group
3 Individual rows in the worksheet
In the worksheet shown in the previous picture, clicking the level 2 button would
hide the rows with data on the sales of individual products, but would leave the row
with the grand total (level 1) and all rows with the subtotals for each product (level
2) visible in the worksheet.
For additional flexibility, you can add levels of detail to the outline that Excel creates,
which enables you to hide specific details from time to time. For instance, you might
want to hide the sales of bamboo barrier, bamboo chimes, and bamboo stakes
(which you know sell well) to see how the other products sell in comparison with
each other.
Create a new outline group within an existing group
1. Select the rows you want to group.
2. Point to Group and Outline on the Data menu, and then click Group.
Excel will create a new group on a new level (level 4), as shown in the
following picture.
Remove a group
1. Select the rows in a group.
2. Point to Group and Outline on the Data menu, and then click Ungroup.
Tip If you want to remove all subtotals from a worksheet, click Subtotal on the
Data menu, and then click Remove All.
To make use of the Split panes
You can view two areas of a worksheet and lock rows or columns in one area by
splitting or freezing panes (pane: A portion of the document window bounded by and
separated from other portions by vertical or horizontal bars.). When you split panes,
you'll be able to scroll in both areas of the worksheet, while rows or columns in the
non-scrolled area remain visible.
When you freeze panes, you select specific rows or columns that remain visible when
scrolling in the worksheet. For example, you would freeze panes to keep row and
column labels visible as you scroll, as shown in the following picture.
Balaji Institute of Technology and Science 120
ITWS Lab Department of Computer Science and Engineering
Lock rows and columns by splitting panes
1. To lock rows, select the row below where you want the split to appear.
To lock columns, select the column to the right of where you want the split to
appear.
To lock both rows and columns, click the cell below and to the right of where
you want the split to appear.
2. On the Window menu, click Split.
3. To remove the split, click Remove Split on the Window menu.
Tip
For a quick way to split panes, point to the split box at the top of the vertical scroll
bar or at the right end of the horizontal scroll bar.
When the pointer changes to a split pointer or , drag the split box down or to the
left to the position you want.
Lock rows and columns by freezing panes
1. To lock rows, select the row below where you want the split to appear.
To lock columns, select the column to the right of where you want the split to
appear.
To lock both rows and columns, click the cell below and to the right of where
you want the split to appear.
2. On the Window menu, click Freeze Panes.
3. To unlock rows, click Unfreeze Panes on the Window menu.
Balaji Institute of Technology and Science 121
ITWS Lab Department of Computer Science and Engineering
Create a PivotTable report
1. Open the workbook where you want to create the PivotTable report.
o If you are basing the report on a Web query, parameter query, report
template, Office Data Connection file, or query file, retrieve the data
into the workbook, and then click a cell in the Microsoft Excel list
containing the retrieved data.
If the retrieved data is from an OLAP database, or the Office Data
Connection returns the data as a blank PivotTable report, continue
with step 6 below.
o If you are basing the report on an Excel list or database, click a cell in
the list or database.
2. On the Data menu, click PivotTable and PivotChart Report.
3. In step 1 of the PivotTable and PivotChart Wizard, follow the instructions, and
click PivotTable under What kind of report do you want to create?
4. Follow the instructions in step 2 of the wizard.
5. Follow the instructions in step 3 of the wizard, and then decide whether to lay
out the report onscreen or in the wizard.
Usually you can lay out the report onscreen, and this method is
recommended. Use the wizard to lay out the report only if you expect
retrieval from a large external data source to be slow, or you need to set
page fields to retrieve data one page at a time. If you aren't sure, try laying
out the report onscreen. You can return to the wizard if necessary.
6. Do one of the following:
Lay out the report onscreen
1. From the PivotTable Field List window, drag the fields with data that you
want to display in rows to the drop area labeled Drop Row Fields Here.
a. If you don't see the field list, click within the outlines of the PivotTable
drop areas, and make sure Show Field List is pressed in.
b. To see what levels of detail are available in fields that have levels, the
click next to the field.
2. Drag fields with data that you want to display across columns to the drop
area labeled Drop Column Fields Here.
3. Drag fields that contain the data that you want to summarize to the area
labeled Drop Data Items Here.
a. If you add more than one data field, arrange these fields in the order
you want: Right-click a data field, point to Order on the shortcut
menu, and use the commands on the Order menu to move the field.
4. Drag fields that you want to use as page fields to the area labeled Drop Page
Fields Here.
5. To rearrange fields, drag them from one area to another. To remove a field,
drag it out of the PivotTable report.
a. To hide the drop area outlines, click a cell outside the PivotTable
report.
Note If data is very slow to appear as you lay out the report, click Always Display
Items on the PivotTable toolbar to turn off initial data display. If retrieval is still
very slow or error messages appear, click PivotTable and PivotChart Report on
the Data menu, and lay out the report in the wizard.
Lay out the report in the wizard
If you've exited from the wizard, click PivotTable and PivotChart Report on the
1. In step 3 of the wizard, click Layout.
Balaji Institute of Technology and Science 122
ITWS Lab Department of Computer Science and Engineering
2. From the group of field buttons on the right, drag the fields that you want
onto the ROW and COLUMN areas in the diagram.
3. Drag the fields that contain the data that you want to summarize onto the
DATA area.
4. Drag fields that you want to use as page fields onto the PAGE area.
a. If you want Excel to retrieve data one page at a time, so you can work
with large amounts of source data, double-click the page field, click
Advanced, click Query external data source as you select each
page field item, and then click OK twice. (This option is unavailable
for some types of source data, including OLAP databases and Office
Data Connections.)
5. To rearrange fields, drag them from one area to another. Some fields can
only be used in some of the areas$$;$$if you drop a field in an area where it can't
be used, the field won't appear in the area.
a. To remove a field, drag it out of the diagram.
b. When you are satisfied with the layout, click OK, and then click
Finish.
Ways to customize PivotTable reports
You can customize the appearance and content of a PivotTable report to get the
presentation you need. In a new report, first display the data you want to see, and
then work on the appearance.
When you click a PivotTable report, blue drop area guidelines appear along with the
PivotTable toolbar and the PivotTable Field List window, so that you can
customize the report.
To add a field, you can drag it from the field list to the area of the report where you
want it, or use the Add To button and dropdown in the field list. To remove a field,
drag it out of the report or drag it back onto the field list. Fields that you remove
remain available in the field list.
You can use fields with icons in the field list only as row (row field: A field that's
assigned a row orientation in a PivotTable report. Items associated with a row field
are displayed as row labels.), column (column field: A field that's assigned a column
orientation in a PivotTable report. Items associated with a column field are displayed
as column labels.), or page fields (page field: A field that's assigned to a page
orientation in a PivotTable or PivotChart report. You can either display a summary of
all items in a page field, or display one item at a time, which filters out the data for
all other items.), and fields with icons only as data fields (data field: A field from a
source list, table, or database that contains data that is summarized in a PivotTable
report or PivotChart report. A data field usually contains numeric data, such as
statistics or sales amounts.). If your fields have these icons, each field can be used
in the report only once.
If your fields have icons, you can use any field in any area, and you can add a field
to both to the data area and to one of the row, column, or page areas, or display it
more than once in the data area, as long as you report doesn't have any calculated
items (calculated item: An item within a PivotTable field or PivotChart field that uses
a formula you create. Calculated items can perform calculations by using the
contents of other items within the same field of the PivotTable report or PivotChart
report.).
You can change the order in which fields appear by dragging them, or in the case of
multiple data fields, by using the Order commands on the PivotTable menu.
Changing the layout
a. Click a column field
b. Drag it to the row area
c. Sport becomes a row field like Region
Balaji Institute of Technology and Science 123
ITWS Lab Department of Computer Science and Engineering
When you move a field, it retains most settings you've made using the arrow in
the field or the Field Settings command, including page field (page field: A field
that's assigned to a page orientation in a PivotTable or PivotChart report. You can
either display a summary of all items in a page field, or display one item at a time,
which filters out the data for all other items.) options and layout settings. For
example, if you set page field settings and move the field to the row area, then later
move the field back to the page area, the settings remain in effect.
Indented and nonindented formats
You can display a PivotTable report in an indented format similar to traditional
banded or formatted database reports, in which the summarized data from each data
field (data field: A field from a source list, table, or database that contains data that
is summarized in a PivotTable report or PivotChart report. A data field usually
contains numeric data, such as statistics or sales amounts.) appears in a single
column. New reports are displayed in a nonindented or crosstabulated format, with
data field values in a grid. Switching to indented format may change the layout of
the report, and it applies an autoformat (autoformat: A built-in collection of cell
formats such as font size, patterns, and alignment that you can apply to a range of
data. Excel determines the levels of summary and detail in the selected range and
applies the formats accordingly.) to the report.
Use Format Report on the PivotTable toolbar to select an indented or
nonindented format. The autoformats available for other worksheet areas are not
available for PivotTable reports.
Indented formats Formats Report 1 through Report 10 are indented formats.
Applying these formats moves all column fields in the report to the row area. Data
fields move to the right of row fields (row field: A field that's assigned a row
orientation in a PivotTable report. Items associated with a row field are displayed as
row labels.), and the field names change to omit the summary function name. For
example, Sum of Sales becomes Sales. After you apply a format, you can rearrange
the fields as in any PivotTable report.
Setting indented format manually If you don't want to apply an autoformat, you
can move all column fields to the row area, double-click each row field, click Layout,
and then click Show items in outline form. This setting is retained if you move the
field to another area, but the field is displayed in indented format only when it is in
the row area.
Nonindented formats Formats PivotTable Classic and Table 1 through Table
10 are nonindented, for use with PivotTable reports that have column fields (column
field: A field that's assigned a column orientation in a PivotTable report. Items
associated with a column field are displayed as column labels.). Table 1 through
Table 10 move the leftmost row field to the column area. Table 1 through Table 5
and Table 7 also add a blank line after each item in the outermost row field.
Character, cell, and number formats
You can change cell formats in a PivotTable report, such as font, background color,
and alignment, as you do for other worksheet cells. You can set number formats for
individual cells or for all cells of a data field.
Most formatting is retained when you refresh (refresh: To update the contents of a
PivotTable or PivotChart report to reflect changes to the underlying source data. If
the report is based on external data, refreshing runs the underlying query to retrieve
new or changed data.) a report or change its layout, provided the Preserve
formatting check box in the PivotTable Options dialog box is selected. Cell border
changes, however, aren't retained.
Changing what's displayed for errors and empty cells Instead of displaying
error values, such as #REF! or #N/A, and blanks for empty cells, you can specify
different values for these cells in a PivotTable report.
Balaji Institute of Technology and Science 124
ITWS Lab Department of Computer Science and Engineering
Using merged cells By default, the labels for items in outer row and column fields
appear left justified at the top of the item group. You can center the items
horizontally and vertically by selecting the Merge labels check box in the
PivotTable Options dialog box.
Adding blank rows between item groups For outer row fields (row field: A field
that's assigned a row orientation in a PivotTable report. Items associated with a row
field are displayed as row labels.), you can add a blank line after each item or its
total row.
Removing formats To remove all character and cell formats in a report, use the
None format available from the Format Report command.
Sorting
In a new report, the items (item: A subcategory of a field in PivotTable and
PivotChart reports. For instance, the field "Month" could have items such as
"January," "February," and so on.) in each field appear either in the order received
from the source database, or in ascending order. Refreshing (refresh: To update the
contents of a PivotTable or PivotChart report to reflect changes to the underlying
source data. If the report is based on external data, refreshing runs the underlying
query to retrieve new or changed data.) a report places new items at the ends of the
rows or columns.
Microsoft Excel uses the following ascending sort order: numbers, text, logical
values, error values such as #REF and #VALUE, and blank cells. When you sort in
descending order, Excel sorts in the reverse order except for blank cells, which are
always sorted last. If you want a sorting sequence such as Jan, Feb, Mar, and so
forth, you can use a custom sort order, and you can also define your own sorting
sequence.
If your report has fields organized in levels, you can sort lower-level items together
by hiding the upper levels before you sort. For example, if you display both the
Country and City levels, cities are sorted separately under each country, but if you
hide the Country level, you can sort cities from different countries together.
You can manually reorder items by clicking and dragging the item labels.
Showing and hiding detail
Your options for varying the amount of detail displayed in a report depend on the
type of source data (source data: The list or table that's used to create a PivotTable
or PivotChart report. Source data can be taken from an Excel list or range, an
external database or cube, or another PivotTable report.) the report is based on.
For OLAP (OLAP: A database technology that has been optimized for querying and
reporting, instead of processing transactions. OLAP data is organized hierarchically
and stored in cubes instead of tables.) source data ( and icons in the field
list), fields are organized in levels of detail, and you can display and hide both
individual items and entire levels. Summary values are usually calculated on the
OLAP server, so underlying detail records for data values usually aren't available for
display. However, your database may have other information available for items,
called property fields (property fields: independent attributes associated with items,
or members, in an OLAP cube. For example, if city items have size and population
properties stored in the server cube, a PivotTable report can display the size and
population of each city.), that you can display or hide. For example, if your database
has a City field, you might be able to display population or climate figures for
individual cities.
For other types of source data ( icons in the field list), you can display and hide
individual items and also display underlying detail records for data values and items,
if this option hasn't been disabled. You can't directly select multiple items in a page
field (page field: A field that's assigned to a page orientation in a PivotTable or
PivotChart report. You can either display a summary of all items in a page field, or
Balaji Institute of Technology and Science 125
ITWS Lab Department of Computer Science and Engineering
display one item at a time, which filters out the data for all other items.), but you
can move the field temporarily to the row or column area, hide some of the items,
and move the field back to the page area, so that the (All) item then displays a
summary that omits the hidden items.
For both types of source data, you can automatically display the top or bottom items
in a field — for example, the top ten sales reps or the five least expensive products.
If you set this type of display for an OLAP field, your setting affects only the current
level and lower levels in the dimension (dimension: An OLAP structure that organizes
data into levels, such as Country/Region/City for a Geography dimension. In a
PivotTable or PivotChart report, each dimension becomes a set of fields where you
can expand and collapse detail.), and remains in effect only if you don't hide the
level you set it for.
Grouping items
You can use grouping to view less detailed summaries — for example, to view data
by quarter instead of week. You can group dates, times, or numbers, and selected
items (item: A subcategory of a field in PivotTable and PivotChart reports. For
instance, the field "Month" could have items such as "January," "February," and so
on.) in a report. Grouping works differently for different types of source data (source
data: The list or table that's used to create a PivotTable or PivotChart report. Source
data can be taken from an Excel list or range, an external database or cube, or
another PivotTable report.).
For OLAP (OLAP: A database technology that has been optimized for querying and
reporting, instead of processing transactions. OLAP data is organized hierarchically
and stored in cubes instead of tables.) source data, when you select and group
individual items, the rest of the items in the field appear in a group named Other.
The new group and the Other group become another level of detail that you can
show or hide, so that you can still display the individual items that you've grouped.
To group items in a page field, you can move the field temporarily to the row or
column area, group the items, and then move the field back to the page area. You
can also select multiple page field items to display as a combined summary.
For other types of source data (icons in the field list), when you select and group
individual items, the items are combined in a new item named Group1 (which you
can rename). You can't display the individual items unless you ungroup them. The
rest of the items in the field are unchanged by adding the group. While items in a
field are grouped, you can't add calculated items (calculated item: An item within a
PivotTable field or PivotChart field that uses a formula you create. Calculated items
can perform calculations by using the contents of other items within the same field of
the PivotTable report or PivotChart report.) to the field. To group items in a page
field, you can move the field temporarily to the row or column area, group the items,
and then move the field back to the page area.
Totals, calculations, and formulas
PivotTable and PivotChart reports (PivotChart report: A chart that provides
interactive analysis of data, like a PivotTable report. You can change views of data,
see different levels of detail, or reorganize the chart layout by dragging fields and by
showing or hiding items in fields.) provide several types of calculations. Data
fields (data field: A field from a source list, table, or database that contains data that
is summarized in a PivotTable report or PivotChart report. A data field usually
contains numeric data, such as statistics or sales amounts.) use summary
functions (summary function: A type of calculation that combines source data in a
PivotTable report or a consolidation table, or when you are inserting automatic
subtotals in a list or database. Examples of summary functions include Sum, Count,
and Average.) to combine values from the underlying source data (source data: The
list or table that's used to create a PivotTable or PivotChart report. Source data can
be taken from an Excel list or range, an external database or cube, or another
PivotTable report.). You can also use custom calculations (custom calculation: A
method of summarizing values in the data area of a PivotTable report by using the
Balaji Institute of Technology and Science 126
ITWS Lab Department of Computer Science and Engineering
values in other cells in the data area. Use the Show data as list on the PivotTable
Field dialog for a data field to create custom calculations. ) to compare data values,
or add your own formulas that use elements of the report or other worksheet data.
Display subtotals for individual fields
1. Double-click the field.
2. Do one of the following:
Subtotal an outer row or column field Click Automatic under
Subtotals. To use a different summary function (summary function: A type
of calculation that combines source data in a PivotTable report or a
consolidation table, or when you are inserting automatic subtotals in a list or
database. Examples of summary functions include Sum, Count, and Average.)
or display more than one type of subtotal, click the summary function you
want in the box to the right of Custom (this option is unavailable for some
types of source data (source data: The list or table that's used to create a
PivotTable or PivotChart report. Source data can be taken from an Excel list
or range, an external database or cube, or another PivotTable report.)).
Subtotal an inner row or column field Click Custom under Subtotals,
if this option is available, and then click a summary function in the box to the
right.
Remove subtotals Click None under Subtotals.
Note If a field contains a calculated item (calculated item: An item within a
PivotTable field or PivotChart field that uses a formula you create. Calculated
items can perform calculations by using the contents of other items within the
same field of the PivotTable report or PivotChart report.), you can't change
the subtotal summary function.
Tip
For outer row fields (row field: A field that's assigned a row orientation in a
PivotTable report. Items associated with a row field are displayed as row
labels.), you can display subtotals above or below their items. Double-click
the field, click Layout, click Show items in outline form, and then select or
clear the Display subtotals at top of group check box.
Display grand totals for the entire report
1. Click the report.
2. On the PivotTable toolbar (toolbar: A bar with buttons and options that you
use to carry out commands. To display a toolbar, click Customize on the
Tools menu, and then click the Toolbars tab.), click PivotTable, and then
click Table Options.
3. Do one of the following:
Display grand totals Select the Grand totals for columns check box,
the Grand totals for rows check box, or both.
Hide grand totals Clear either or both check boxes.
Note Grand totals for a field use the same summary function (summary
function: A type of calculation that combines source data in a PivotTable
report or a consolidation table, or when you are inserting automatic subtotals
in a list or database. Examples of summary functions include Sum, Count, and
Average.) as the subtotals for the field.
Calculate the totals with or without hidden items
1. Click the report.
2. On the PivotTable toolbar (toolbar: A bar with buttons and options that you
use to carry out commands. To display a toolbar, click Customize on the
Tools menu, and then click the Toolbars tab.), click Include Hidden Items
in Totals .
If this button is unavailable, your source data allows you to include or exclude
hidden items in page fields (page field: A field that's assigned to a page
orientation in a PivotTable or PivotChart report. You can either display a
Balaji Institute of Technology and Science 127
ITWS Lab Department of Computer Science and Engineering
summary of all items in a page field, or display one item at a time, which
filters out the data for all other items.): click PivotTable, click Table
Options, and then select or clear the Subtotal hidden page items check
box.
1. the data field (data field: A field from a source list, table, or database that
contains data that is summarized in a PivotTable report or PivotChart report.
A data field usually contains numeric data, such as statistics or sales
amounts.) or a cell in the data area.
For a PivotChart report (PivotChart report: A chart that provides interactive
analysis of data, like a PivotTable report. You can change views of data, see
different levels of detail, or reorganize the chart layout by dragging fields and
by showing or hiding items in fields.), work in the associated PivotTable
report (associated PivotTable report: The PivotTable report that supplies the
source data to the PivotChart report. It is created automatically when you
create a new PivotChart report. When you change the layout of either report,
the other also changes.).
2. On the PivotTable toolbar (toolbar: A bar with buttons and options that you
use to carry out commands. To display a toolbar, click Customize on the
Tools menu, and then click the Toolbars tab.), click Field Settings .
3. In the Summarize by box, click the summary function (summary function: A
type of calculation that combines source data in a PivotTable report or a
consolidation table, or when you are inserting automatic subtotals in a list or
database. Examples of summary functions include Sum, Count, and Average.)
you want to use.
For some types of source data (source data: The list or table that's used to
create a PivotTable or PivotChart report. Source data can be taken from an
Excel list or range, an external database or cube, or another PivotTable
report.), and for calculated fields (calculated field: A field in a PivotTable
report or PivotChart report that uses a formula you create. Calculated fields
can perform calculations by using the contents of other fields in the
PivotTable report or PivotChart report.) and fields with calculated
items (calculated item: An item within a PivotTable field or PivotChart field
that uses a formula you create. Calculated items can perform calculations by
using the contents of other items within the same field of the PivotTable
report or PivotChart report.), you can't change the summary function.
4. If you want to use a custom calculation (custom calculation: A method of
summarizing values in the data area of a PivotTable report by using the
values in other cells in the data area. Use the Show data as list on the
PivotTable Field dialog for a data field to create custom calculations.), click
Options, click the calculation you want in the Show data as list, and then
select a Base field and Base item, if these options are available for the
calculation you chose, to provide the data for the calculation. The base field
should not be the same one you chose in step 1.
Note Setting Show data as to Normal turns off custom calculation.
5. If the report has multiple data fields, repeat these steps for each one that you
want to change.
6. If your source data allows you to change the summary function, you can use
more than one summary method for the same field. Drag the field from the
PivotTable Field List window to the data area a second time, and then
repeat the steps above for the second instance of the field.
Note When you change the summary method in a PivotChart report or its
associated PivotTable report, some chart formatting may be lost.
Change the amount of detail displayed in a PivotTable report
1. Determine what kind of source data (source data: The list or table that's used
to create a PivotTable or PivotChart report. Source data can be taken from an
Balaji Institute of Technology and Science 128
ITWS Lab Department of Computer Science and Engineering
Excel list or range, an external database or cube, or another PivotTable
report.) your report has: click the report, if the field list is not displayed click
Show Field List on the PivotTable toolbar, and look at the PivotTable
Field List window.
2. For OLAP reports, display or hide different levels of detail for a field.
How?
1. Click the field.
2. To display or hide lower-level detail, click Show Detail or Hide Detail
on the PivotTable toolbar.
3. To hide upper levels of detail, right-click the field button (field button:
Button that identifies a field in a PivotTable or PivotChart report. You
can drag the field buttons to change the layout of the report, or click
the arrows next to the buttons to change the level of detail displayed
in the report.) for the lowest level you want to hide, and then click
Hide levels on the shortcut menu.
The level you clicked and all higher levels in the
dimension (dimension: An OLAP structure that organizes data into
levels, such as Country/Region/City for a Geography dimension. In a
PivotTable or PivotChart report, each dimension becomes a set of
fields where you can expand and collapse detail.) are removed from
view, and the dropdown arrow is also hidden.
To redisplay hidden upper levels, right-click any field button in the
dimension, and then click Show levels on the shortcut menu.
For non-OLAP reports, do one or more of the following:
Display or hide detail data for an item
1. Click the item.
2. On the PivotTable toolbar, click Show Detail or Hide Detail .
3. If prompted, click the field that has the detail data you want to see.
Display or hide detail for a data cell
1. Double-click a cell in the data area (data area: The part of a PivotTable
report that contains summary data. Values in each cell of the data
area represent a summary of data from the source records or rows.).
Microsoft Excel places the detail data summarized in the cell on a new
worksheet.
2. To hide the detail data, delete the new worksheet.
2. For OLAP reports, display or hide property fields (property fields:
independent attributes associated with items, or members, in an OLAP cube.
For example, if city items have size and population properties stored in the
server cube, a PivotTable report can display the size and population of each
city.), if available from your server cube.
How?
1. Click the field in the dimension for which you want to display property
fields.
2. On the PivotTable toolbar, click PivotTable, and then click Property
Fields.
3. In the Choose properties from level list, click each level for which
you want to display property fields, and then double-click the property
fields you want to see.
4. In the Properties to display box, use the and buttons to
arrange the property fields in the order you want them to appear in
the report.
5. Make sure the Show fields for this dimension in outline form
check box is selected, and then click OK.
Balaji Institute of Technology and Science 129
ITWS Lab Department of Computer Science and Engineering
6. If the levels for which you selected property fields aren't displayed in
the report, click the field and then click Show Detail on the
PivotTable toolbar.
Group items in a PivotTable or PivotChart field
1. If the field is a page field (page field: A field that's assigned to a page
orientation in a PivotTable or PivotChart report. You can either display a
summary of all items in a page field, or display one item at a time, which
filters out the data for all other items.), check the page field settings, and
then move it temporarily to the row or column area.
How?
For a PivotChart report, work in the associated PivotTable report (associated
PivotTable report: The PivotTable report that supplies the source data to the
PivotChart report. It is created automatically when you create a new
PivotChart report. When you change the layout of either report, the other also
changes.).
1. Double-click the page field.
3. Make sure the Retrieve external data for all page field items
option is either selected or unavailable.
4. Click OK twice.
5. Drag the page field to the row or column area.
2. Do one of the following:
Group numeric items
1. Right-click the field with the numeric items, point to Group and Show
Details on the shortcut menu, and then click Group.
2. In the Starting at box, enter the first item to group.
3. In the Ending at box, enter the last item to group.
4. In the By box, type the number of items that you want in each group.
Group dates or times
5. Right-click the field with the dates or times, point to Group and Show
Details on the shortcut menu, and then click Group.
6. Enter the first date or time to group in the Starting at box, and enter
the last date or time to group in the Ending at box.
7. In the By box, click one or more time periods for the groups.
To group items by weeks, click Days in the By box, make sure Days
is the only time period selected, and then click 7 in the Number of
days box. You can then click additional time periods to group by, such
as Month, if you want.
Group selected items
8. Select the items to group, either by clicking and dragging, or by
holding down CTRL or SHIFT while you click.
For a PivotChart report, select the items in the associated PivotTable
report (associated PivotTable report: The PivotTable report that
supplies the source data to the PivotChart report. It is created
automatically when you create a new PivotChart report. When you
change the layout of either report, the other also changes.).
9. Right-click the selected items, point to Group and Show Details on
the shortcut menu, and then click Group.
Balaji Institute of Technology and Science 130
ITWS Lab Department of Computer Science and Engineering
Note For fields organized in levels, you can only group items that all have
the same next-level item. For example, if the field has levels Country and
City, you can't group cities from different countries.
Ungroup items
o Right-click the group, point to Group and Show Details on the
shortcut menu, and then click Ungroup.
In a numeric or date/time field, right-click any group$$;$$Excel then
ungroups all groups for the field.
3. If the field was formerly a page field, drag it back to the page area.
Print a PivotTable report
1. If you have more than one PivotTable report on the worksheet, set a print
area that includes only the report you want to print.
How?
1. Click the report.
2. On the PivotTable toolbar, click PivotTable, point to Select, and
then click Entire Table.
3. On the File menu, point to Print Area, and then click Set Print Area.
2. On the File menu, click Page Setup, and adjust the page settings, sheet
settings, margins, and headers and footers.
3. If you want to repeat the row and column labels from the report on each page
as print titles, clear the Rows to repeat at top and Columns to repeat at
left boxes, and then set PivotTable print titles.
How?
1. On the PivotTable toolbar, click PivotTable, and then click Table
Options.
2. Under Format options, select the Set print titles check box.
3. If your report has more than one row field and you also want to repeat
outer row field items on each page, select the Repeat item labels on
each printed page check box.
4. If your report has more than one row field and you want automatic page
breaks after each item in one or more outer row fields, set these page breaks.
How?
1. Double-click the outer row field that has the items you want to print on
separate pages.
2. Click Layout.
3. Select the Insert page break after each item check box.
5. On the View menu, click Page Break Preview, and make any adjustments
you want to the page breaks.
You can insert new manual page breaks and move and delete automatic page
breaks.
6. On the File menu, click Print Preview, and check your print layout. To make
adjustments, you can repeat any of the previous steps as needed.
7. When the preview looks correct, click Print
Custom calculations for PivotTable and PivotChart data fields
The following functions are available for custom calculations in data fields.
Function Result
Difference Displays data as the difference from the value of the Base item in
From the Base field.
Balaji Institute of Technology and Science 131
ITWS Lab Department of Computer Science and Engineering
% Of Displays data as a percentage of the value of the Base item in the
Base field.
% Difference Displays data as the percentage difference from the value of the
From Base item in the Base field.
Running Total Displays the data for successive items in the Base field as a
in running total.
% Of Row Displays the data in each row or category as a percentage of the
total for the row or category.
% Of Column Displays all the data in each column or series as a percentage of the
total for the column or series.
% Of Total Displays data as a percentage of the grand total of all the data or
data points in the report.
Index Calculates data as follows:
((value in cell) x (Grand Total of Grand Totals)) / ((Grand Row
Total) x (Grand Column Total))
Delete a PivotTable or PivotChart formula
For best results in a PivotChart report (PivotChart report: A chart that provides
interactive analysis of data, like a PivotTable report. You can change views of data,
see different levels of detail, or reorganize the chart layout by dragging fields and by
showing or hiding items in fields.), work in the associated PivotTable
report (associated PivotTable report: The PivotTable report that supplies the source
data to the PivotChart report. It is created automatically when you create a new
PivotChart report. When you change the layout of either report, the other also
changes.).
1. Determine whether the formula is in a calculated field (calculated field: A field
in a PivotTable report or PivotChart report that uses a formula you create.
Calculated fields can perform calculations by using the contents of other fields
in the PivotTable report or PivotChart report.) or a calculated item (calculated
item: An item within a PivotTable field or PivotChart field that uses a formula
you create. Calculated items can perform calculations by using the contents of
other items within the same field of the PivotTable report or PivotChart
report.).
Calculated fields appear in the PivotTable Field List window. Calculated items
appear as items (item: A subcategory of a field in PivotTable and PivotChart
reports. For instance, the field "Month" could have items such as "January,"
"February," and so on.) within other fields.
2. Do one of the following:
Delete a calculated field
1. Click the report.
2. On the PivotTable toolbar (toolbar: A bar with buttons and options
that you use to carry out commands. To display a toolbar, use the
Customize dialog box (point to Toolbars on the View menu and click
Customize). To see more buttons, click Toolbar Options at the end
of the toolbar.), click PivotTable or PivotChart, point to Formulas,
and then click Calculated Field.
3. In the Name box, click the field you want to delete.
4. Click Delete.
Balaji Institute of Technology and Science 132
ITWS Lab Department of Computer Science and Engineering
Delete a calculated item
5. Click the field with the item you want to delete.
6. On the PivotTable toolbar (toolbar: A bar with buttons and options
that you use to carry out commands. To display a toolbar, use the
Customize dialog box (point to Toolbars on the View menu and click
Customize). To see more buttons, click Toolbar Options at the end
of the toolbar.), click PivotTable or PivotChart, point to Formulas,
and then click Calculated Item.
7. In the Name box, click the item you want to delete.
8. Click Delete.
Note When you delete a formula from a PivotChart report or its associated
PivotTable report, some chart formatting may be lost.
Tip
If you don't want to delete a formula permanently, you can hide the field or item. To
hide a field, drag it out of the report, or click the dropdown arrow in the Data field
and then clear its check box$$;$$it remains available in the field list. To hide an item,
click the dropdown arrow in its field, and then clear the check box for the item.
Making use of Field buttons
Hiding the field buttons (field button: Button that identifies a field in a PivotTable or
PivotChart report. You can drag the field buttons to change the layout of the report,
or click the arrows next to the buttons to change the level of detail displayed in the
report.) also hides the page field drop area (drop area: An area in a PivotTable or
PivotChart report where you can drop fields from the Field List dialog box to display
the data in the field. The labels on each drop area indicate the types of fields you can
create in the report.), if your report doesn't have any page fields (page field: A field
that's assigned to a page orientation in a PivotTable or PivotChart report. You can
either display a summary of all items in a page field, or display one item at a time,
which filters out the data for all other items.).
1. Click the PivotChart report.
2. On the PivotTable toolbar (toolbar: A bar with buttons and options that you
use to carry out commands. To display a toolbar, click Customize on the
Tools menu, and then click the Toolbars tab.), click PivotChart, and then
select or clear the Hide PivotChart Field Buttons command.
Tip
If you hide field buttons but want to label elements of your chart that were
previously identified by field button names, you can add axis titles or text boxes to
the chart.
To make data entry easier, or to limit entries to certain items that you define, you
can create a drop-down list that gets its choices from cells elsewhere on the
worksheet.
1. Type the entries for the drop-down list in a single column or row. Do not
include blank cells in the list.
If you type the list on a different worksheet from the data entry cell, define a
name (name: A word or string of characters that represents a cell, range of
cells, formula, or constant value. Use easy-to-understand names, such as
Products, to refer to hard to understand ranges, such as Sales!C20:C30.) for
the list.
How?
selection: A selection of two or more cells or ranges that don't touch
each other. When plotting nonadjacent selections in a chart, make
Balaji Institute of Technology and Science 133
ITWS Lab Department of Computer Science and Engineering
sure that the combined selections form a rectangular shape.) that you
want to name.
2. Click the Name box at the left end of the formula bar (formula bar: A
bar at the top of the Excel window that you use to enter or edit values
or formulas in cells or charts. Displays the constant value or formula
stored in the active cell.) .
Name box
3. Type the name for the cells.
4. Press ENTER.
How?
1. Open the workbook that contains the list of drop-down entries.
2. Open the workbook where you want to validate cells, point to Name
on the Insert menu, and then click Define.
3. In the Names in workbook box, type the name.
4. In the Refers to box, delete the contents, and keep the insertion
pointer in the box.
5. On the Window menu, click the name of the workbook that contains
the list of drop-down entries, and then click the worksheet that
contains the list.
6. Select the cells containing the list.
7. In the Define Name dialog box, click Add, and then click Close.
2. Select the cell where you want the drop-down list.
3. On the Data menu, click Validation, and then click the Settings tab.
4. In the Allow box, click List.
5. If the list is in the same worksheet, enter a reference to your list in the
Source box.
If the list is elsewhere, enter the name you defined for your list in the Source
box.
Make sure the reference or name is preceded with an equal sign (=).
6. Make sure the In-cell drop-down check box is selected.
7. Specify whether the cell can be left blank: Select or clear the Ignore blank
check box.
8. To display optional input instructions when the cell is clicked, click the Input
Message tab, make sure the Show input message when cell is selected
check box is selected, and then fill in the title and text for the message.
9. Specify how you want Microsoft Excel to respond when invalid data is entered.
How?
1. Click the Error Alert tab, and make sure the Show error alert after
invalid data is entered check box is selected.
2. Select one of the following options for the Style box:
To display an information message that does not prevent entry of
invalid data, click Information.
To display a warning message that does not prevent entry of invalid
data, click Warning.
To prevent entry of invalid data, click Stop.
3. Fill in the title and text for the message (up to 225 characters).
Note If you don't enter a title or text, the title defaults to " Microsoft
Excel" and the message to: "The value you entered is not valid. A user
has restricted values that can be entered into this cell."
Importing data
Importing data from databases and files
Balaji Institute of Technology and Science 134
ITWS Lab Department of Computer Science and Engineering
You can import data to Excel from most data sources by pointing to Import
External Data on the Data menu, clicking Import Data, and then choosing the
data you want to import in the Select Data Source dialog box.
The Data Connection Wizard, available when you click New Source in the Select
Data Source dialog box, makes it possible to import data from external data
connections not available from the Select Data Source dialog box. These sources
may include OLE DB data sources (including OLAP cubes and exchange servers) and
any data sources a system administrator supplies. You cannot filter or join data in
the Data Connection Wizard.
The default connection method when you import data using the Data Connection
Wizard is through OLE DB providers. The resulting .odc (office data connection) files
can be opened for viewing in Internet Explorer and edited in Excel, Notepad, and
other Microsoft Office applications if the file doesn't point to an OLAP data source.
The Data Connection Wizard also provides access to a data source called a data
retrieval service. A data retrieval service is a Web service installed on Windows
SharePoint Services for connecting to and retrieving data. To use a data retrieval
service, a client application, such as Excel, sends a query request over HTTP (HTTP:
Internet protocol that delivers information on the World Wide Web. Makes it possible
for a user with a client program to enter a URL (or click a hyperlink) and retrieve
text, graphics, sound, and other digital information from a Web server.) to the data
retrieval service on Windows SharePoint Services. The data retrieval service sends
that request to the data source, and then passes the data that is returned to it back
to the client application as XML. Importing data from a data retrieval service in Excel
automatically creates a databound XML list in your worksheet. After adding a
databound XML list to your worksheet, you can use the commands on the XML
submenu of the Data menu or the List tool bar to refresh data, edit the query, or
set the properties of the XML map associated with the XML list.
A default installation of Windows SharePoint Services provides a data retrieval
service for connecting to data in SharePoint lists. A SharePoint site administrator can
install the Microsoft Office Web Parts and Components to add additional data
retrieval services for Microsoft SQL Server and Microsoft Business Solutions. The
installation program for Microsoft Office Web Parts and Components is available on
Importing data with Microsoft Query
In most cases, you can import data by using the Import Data command as
described in the section above. Use Query or another program only if you need to
perform specialized query tasks such as the following:
Filter rows or columns of data before they are brought into Excel.
Create a parameter query (parameter query: A type of query that, when you
run it, prompts for values (criteria) to use to select the records for the result
set so that the same query can be used to retrieve different result sets.).
Sort data before it is brought into Excel.
Join multiple tables.
Microsoft Query provides a simple front end, easily accessible from within Excel, to
You can use Query to set up ODBC data sources to retrieve data. In Query, you can
use the Query Wizard to create a simple query (query: In Query or Access, a means
stored in a database.), or you can use advanced criteria in Query to create a more
complex query. You can access Query from Excel, or you can create a query from
within the PivotTable and PivotChart Wizard.
You can also use Dynamic Data Exchange (DDE) (Dynamic Data Exchange (DDE): An
established protocol for exchanging data between Microsoft Windows-based
To import data using Query, you must first:
Balaji Institute of Technology and Science 135
ITWS Lab Department of Computer Science and Engineering
Install Query Query, including the Query Wizard, is an optional feature for
Excel. Under most circumstances, you are prompted to install Query when
you point to Import External Data on the Data menu and click New
Database Query.
Install ODBC drivers An ODBC driver (Open Database Connectivity
(ODBC) driver: A program file used to connect to a particular database. Each
database program, such as Access or dBASE, or database management
system, such as SQL Server, requires a different driver.) is required to
retrieve data in relational databases, text files, or Excel using Query. When
you install Query, you automatically install a set of ODBC drivers. If you use a
driver other than one installed with Query, you must install the driver
separately.
Install data source drivers A data source driver (data source driver: A
program file used to connect to a specific database. Each database program
or management system requires a different driver.) is required to retrieve
OLAP source data. Query supports connecting to databases that are created
by using SQL Server OLAP Services$$;$$when you installed Query, you
automatically installed support for this type of OLAP database. To connect to
other OLAP databases, you must install a data source driver and client
software.
Importing data from the Web
You can import data originating from a Web page by pointing to Import External
World Wide Web (World Wide Web (WWW): The multimedia branch of the Internet
that presents not only text, but also graphics, sound, and video. On the Web, users
can easily jump from item to item, page to page, or site to site by using hyperlinks.)
through your company's intranet or through a modem on your computer or network,
or you can make a query against local HTML or XML sources.
Importing data with Visual Basic for Applications (VBA)
You can use a Visual Basic for Applications (VBA: A macro-language version of
Microsoft Visual Basic that is used to program Windows applications and is included
with several Microsoft applications.) macro (macro: An action or a set of actions you
can use to automate tasks. Macros are recorded in the Visual Basic for Applications
Depending on the data source, you will use either ActiveX Data Objects (ActiveX
Data Objects (ADO): A data access interface that communicates with OLE DB-
compliant data sources to connect to, retrieve, manipulate, and update data.) or
Data Access Objects (Data Access Objects (DAO): A data access interface that
communicates with Microsoft Jet and ODBC-compliant data sources to connect to,
retrieve, manipulate, and update data and the database structure.) to retrieve data
using VBA.
If you want to use a macro that you created in Excel version 5.0 or earlier, click
selected.
For information about creating Visual Basic for Applications macros, see Visual Basic
Help (Microsoft Visual Basic Help: To get help for Visual Basic in Excel, point to
Macro on the Tools menu, and then click Visual Basic Editor. On the Help menu,
click Microsoft Visual Basic Help.).
Note While you are recording a macro that includes a query, Excel can't run the
query in the background, even if you chose to run it that way. To change the
recorded macro so that it runs in the background, edit the macro in the Visual Basic
Editor and change the refresh method for the QueryTable object from
"BackgroundQuery := False" to "BackgroundQuery := True".
Refreshing data and naming ranges
Refreshing data
Balaji Institute of Technology and Science 136
ITWS Lab Department of Computer Science and Engineering
Excel provides many options for refreshing imported data, including refreshing the
data whenever you open the workbook and automatically refreshing data at timed
intervals. You can continue to work in Excel while data is being refreshed, and you
can also check the status of the refresh while it's being refreshed.
If your external data source (data source: A stored set of "source" information used
to connect to a database. A data source can include the name and location of the
database server, the name of the database driver, and information that the database
needs when you log on.) requires a password (password: A word, phrase, or string
you can require that the password is entered each time the external data
range (external data range: A range of data that is brought into a worksheet but that
originates outside of Excel, such as in a database or text file. In Excel, you can
format the data or use it in calculations as you would any other data.) is refreshed.
When an external data range expands and additional records are returned, Excel can
fill formulas in adjacent columns or within the data range so that they remain next to
the appropriate data.
You can also choose how to add new data to your worksheet.
Naming external data ranges
Excel automatically names an external data range as follows:
External data ranges from Office Data Connection (Office Data Connection
(ODC) file: A file that stores information about a connection to a data source
(such as an OLE DB data source) and the data associated with the
connection.) (ODC) files are named with the .odc file extension.
External data ranges from databases are named with the name of the query;
by default Query_from_source is the name of the data source you used to
create the query.
External data ranges from text files are named with the text file name.
External data ranges from Web queries (Web query: A query that retrieves
data stored on your intranet or the Internet.) are named with the name
of the Web page from which the data was retrieved.
If your worksheet has more than one external data range from the same source, the
ranges are numbered. For example, MyText, MyText_1, MyText_2, and so on.
You can also change the name of an external data range in the Data Range
Properties dialog box
Balaji Institute of Technology and Science 137
ITWS Lab Department of Computer Science and Engineering
To make use of the Filtering Concept
Filtering is a quick and easy way to find and work with a subset of data in a range. A
filtered range displays only the rows that meet the criteria (criteria: Conditions you
specify to limit which records are included in the result set of a query or filter.) you
specify for a column. Microsoft Excel provides two commands for filtering ranges:
Unlike sorting, filtering does not rearrange a range. Filtering temporarily hides rows
you do not want displayed. When Excel filters rows, you can edit, format, chart, and
print your range subset without rearranging or moving it.
Use AutoFilter for simple criteria and to filter by selection
When you use the AutoFilter command, AutoFilter arrows appear to the right of
the column labels in the filtered range.
Unfiltered range
Filtered range
Microsoft Excel indicates the filtered items with blue.
You use custom AutoFilter to display rows that contain either one value or another.
You can also use custom AutoFilter to display rows that meet more than one
condition for a column$$;$$for example, you might display rows that contain values
within a specific range (such as a value of Davolio).
Top of Page
Use Advanced Filter for more complex criteria
The Advanced Filter command on the Data menu lets you use complex
criteria (criteria: Conditions you specify to limit which records are included in the
result set of a query. For example, the following criterion selects records for which
the value for the Order Amount field is greater than 30,000: Order Amount >
30000.) to filter a range, but it works differently from the AutoFilter command in
several important ways.
It displays the Advanced Filter dialog box instead of the Custom AutoFilter
dialog box.
You do not type the complex criteria in the Advanced Filter dialog box as
you do in the Custom AutoFilter dialog box. Rather, you type the complex
criteria in a criteria range on the worksheet and above the range you want to
Balaji Institute of Technology and Science 138
ITWS Lab Department of Computer Science and Engineering
filter. Excel uses the separate criteria range in the Advanced Filter dialog
box as the source for the complex criteria.
Although you can filter a range in place, like the AutoFilter command, the
Advanced Filter command does not display drop-down lists for the columns.
Filter for unique records
Select the column or click a cell in the range or list you want to filter.
On the Data menu, point to Filter, and then click Advanced Filter.
Do one of the following.
o To filter the range or list in place, similar to using AutoFilter, click
Filter the list, in-place.
o To copy the results of the filter to another location, click Copy to
another location. Then, in the Copy To box, enter a cell reference.
To select a cell, click Collapse Dialog to temporarily hide the
dialog box. Select the cell on the worksheet, and then press Expand
Dialog .
Select the Unique records only check box.
Note Once you filter for unique values, you can copy them to another worksheet
and then archive or delete the original worksheet.
Filters for different type of data cells
Filter for the smallest or largest number
1. Click the arrow in the column that contains the numbers, and click
(Top 10...).
2. In the box on the left, click Top, or Bottom.
3. In the box in the middle, enter a number.
4. In the box on the right, click Items.
Filter a range for rows that contain specific text
1. Click the arrow in the column that contains the numbers, and click
(Custom).
2. In the box on the left, click equals, or does not equal, contains, or
does not contain.
3. In the box on the right, enter the text you want.
4. If you need to find text values that share some characters but not
others, use a wildcard character.
How?
The following wildcard characters can be used as comparison
criteria (criteria: Conditions you specify to limit which records are
included in the result set of a query or filter.) for filters, and when
searching and replacing content.
Use To find
Any single character
? (question mark) For example, sm?th finds "smith" and
"smyth"
Any number of characters
* (asterisk) For example, *east finds "Northeast" and
"Southeast"
~ (tilde) followed by ?, *, A question mark, asterisk, or tilde
or ~ For example, fy91~? finds "fy91?"
1. To add another criteria, click And or Or, and repeat the previous step.
Filter for blank or nonblank cells
Click the arrow in the column that contains the numbers, then click
(Blanks) or (NonBlanks).
Note The Blanks and NonBlanks options are available only if the column
you want to filter contains a blank cell.
Balaji Institute of Technology and Science 139
ITWS Lab Department of Computer Science and Engineering
Filter for numbers greater than or less than another number
1. Click the arrow in the column that contains the numbers, and click
(Custom).
2. In the box on the left, click is greater than, is less than, is greater
than or equal to, or is less than or equal to.
3. In the box on the right, enter a number.
4. To add another criteria, click And or Or, and repeat the previous step.
Filter for a number equal to or not equal to another number
1. Click the arrow in the column that contains the numbers, and click
(Custom).
2. In the box on the left, click equals, or does not equal.
3. In the box on the right, enter a number.
4. To add another criteria, click And or Or, and repeat the previous step.
Filter for the beginning or end of a text string
1. Click the arrow in the column that contains the numbers, and click
(Custom).
2. In the box on the left, click begins with, or does not begin with, or
ends with, or does not end with.
3. In the box on the right, enter the text you want.
4. If you need to find text values that share some characters but not
others, use a wildcard character.
How?
The following wildcard characters can be used as comparison
criteria (criteria: Conditions you specify to limit which records are
included in the result set of a query or filter.) for filters, and when
searching and replacing content.
Use To find
Any single character
? (question mark) For example, sm?th finds "smith" and
"smyth"
Any number of characters
* (asterisk) For example, *east finds "Northeast" and
"Southeast"
~ (tilde) followed by ?, *, A question mark, asterisk, or tilde
or ~ For example, fy91~? finds "fy91?"
1. To add another criteria, click And or Or, and repeat the previous step.
Filter for the top or bottom numbers by percent
1. Click the arrow in the column that contains the numbers, and click
(Top 10...).
2. In the box on the left, click Top or Bottom.
3. In the box in the middle, enter a number.
4. In the box on the right, click Percent.
Notes
When you apply a filter to a column, the only filters available for other
columns are the values visible in the currently filtered range.
Only the first 1000 unique entries in a list appear when you click the arrow
.
To Protect Workbook
Balaji Institute of Technology and Science 140
ITWS Lab Department of Computer Science and Engineering
To allow only authorized users to view or modify your data, you can help secure your
workbook, worksheet, or part of a worksheet. Excel passwords can be up to 255
letters, numbers, spaces, and symbols. You must type uppercase and lowercase
letters correctly when you set and enter passwords.).
1. On the File menu, click Save As.
2. On the Tools menu, click General Options.
3. Do either or both of the following:
o If you want users to enter a password (password: A way to restrict
passwords can be up to 255 letters, numbers, spaces, and symbols.
You must type uppercase and lowercase letters correctly when you set
and enter passwords.) before they can view the workbook, type a
o If you want users to enter a password before they can save changes to
passwords you specify in the Password to modify box are not encrypted.
These passwords are only meant to give specific users permission to modify
workbook data. For optimal password security, it's best to assign both
provide specific users with permission to modify its content.
Important Use strong passwords that combine uppercase and lowercase
letters, numbers, and symbols. Weak passwords don't mix these elements.
password that you can remember so that you don't have to write it down.
4. If you want to use a different encryption type, click Advanced, click the type
you want in the Choose an encryption type list, and then click OK.
5. If needed, specify the number of characters you want in the Choose a key
length box.
Note Document property encryption is enabled by default for most
encryption types and providers. It prevents unauthorized users from viewing
summary and custom file properties (such as the author or any custom file
information) in the Properties dialog box. When users right-click the
password-protected file, and then click Properties, information won't be
available on the Summary tab and Custom tab. Authorized users, however,
can open the file and view all file properties (File menu, Properties
command). To disable document property encryption, clear the Encrypt
document properties check box.
6. Click OK.
8. Click Save.
9. If prompted, click Yes to replace the existing workbook.
Note You can also secure a workbook with a password on the Security tab of the
Options dialog box (Tools menu, Options command).
Workbook elements
Protect workbook elements
1. On the Tools menu, point to Protection, and then click Protect Workbook.
2. Do one or more of the following:
o To protect the structure of a workbook so that worksheets in the
workbook can't be moved, deleted, hidden, unhidden, or renamed, and
new worksheets can't be inserted, select the Structure check box.
o To protect windows so that they are the same size and position each
time the workbook is opened, select the Windows check box.
Balaji Institute of Technology and Science 141
ITWS Lab Department of Computer Science and Engineering
o To prevent others from removing workbook protection, type a
Protect elements in a shared workbook
1. If the workbook is already shared (shared workbook: A workbook set up to
allow multiple users on a network to view and make changes at the same
time. Each user who saves the workbook sees the changes made by other
users.), and you want to assign a password to protect the sharing, unshare
the workbook.
How?
1. Have all other users save and close the shared workbook. If other
users are editing, they will lose any unsaved work.
2. Unsharing the workbook deletes the change history (change history:
In a shared workbook, information that is maintained about changes
made in past editing sessions. The information includes the name of
the person who made each change, when the change was made, and
what data was changed.). If you want to keep a copy of this
information, print out the History worksheet (History worksheet: A
separate worksheet that lists changes being tracked in a shared
workbook, including the name of the person who made the change,
when and where it was made, what data was deleted or replaced, and
how conflicts were resolved.) or copy it to another workbook.
How?
1. On the Tools menu, point to Track Changes, and then click
Highlight Changes.
2. In the When box, click All.
3. Clear the Who and Where check boxes.
4. Select the List changes on a new sheet check box, and then
click OK.
5. Do one or more of the following:
To print the History worksheet, click Print .
To copy the history to another workbook, select the cells
you want to copy, click Copy , switch to another
workbook, click where you want the copy to go, and
click Paste .
Note You may also want to save or print the current version of
the workbook, because this history might not apply to later
versions. For example, cell locations, including row numbers, in
the copied history may no longer be current.
3. On the Tools menu, click Share Workbook, and then click the
Editing tab.
4. Make sure that you are the only person listed in the Who has this
workbook open now box.
5. Clear the Allow changes by more than one user at the same time
check box.
If this check box is not available, you must unprotect the workbook
before clearing the check box.
How?
1. Click OK, point to Protection on the Tools menu, and then
click Unprotect Shared Workbook.
2. Enter the password if prompted, and then click OK.
3. On the Tools menu, click Share Workbook, and then click the
Editing tab.
6. When prompted about the effects on other users, click Yes.
Balaji Institute of Technology and Science 142
ITWS Lab Department of Computer Science and Engineering
2. Set other types of protection if you want: Give specific users access to
ranges, protect worksheets, protect workbook elements, and set passwords
for viewing and editing.
3. On the Tools menu, point to Protection, and then click Protect Shared
Workbook or Protect and Share Workbook.
4. Select the Sharing with track changes check box.
5. If you want to require other users to supply a password to turn off the
change history (change history: In a shared workbook, information that is
includes the name of the person who made each change, when the change
was made, and what data was changed.) or remove the workbook from
shared use, type the password in the Password box, and then retype the
6. If prompted, save the workbook.
To Protect Worksheets
To prevent anyone from accidentally or deliberately changing, moving, or deleting
important data, you can protect certain worksheet (worksheet: The primary
document that you use in Excel to store and work with data. Also called a
spreadsheet. A worksheet consists of cells that are organized into columns and rows;
a worksheet is always stored in a workbook.) or workbook elements, with or without
a worksheet. Excel passwords can be up to 255 letters, numbers, spaces, and
symbols. You must type uppercase and lowercase letters correctly when you set and
Important Worksheet or workbook element protection should not be confused with
file security. It is not meant to make your workbook more secure, and cannot protect
it from users who have malicious intent.
Worksheet elements
Protect worksheet elements from all users
1. Switch to the worksheet you want to protect.
2. Unlock any cells you want users to be able to change: Select each cell or
range, click Cells on the Format menu, click the Protection tab, and then
clear the Locked check box.
3. Hide any formulas that you don't want to be visible: Select the cells with the
formulas, click Cells on the Format menu, click the Protection tab, and
then select the Hidden check box.
4. Unlock any graphic objects you want users to be able to change.
How?
You don't need to unlock buttons or controls for users to be able to click and
use them. You can unlock embedded charts, text boxes, and other objects
created with the drawing tools that you want users to be able to modify. To
see which elements on a worksheet are graphic objects, click Go To on the
Edit menu, click Special, and then click Objects.
1. Hold down CTRL and click each object that you want to unlock.
2. On the Format menu, click the command for the object you selected:
AutoShape, Object, Text Box, Picture, Control, or WordArt.
3. Click the Protection tab.
4. Clear the Locked check box, and if present, clear the Lock text check
box.
5. On the Tools menu, point to Protection, and then click Protect Sheet.
6. Type a password for the sheet.
Balaji Institute of Technology and Science 143
ITWS Lab Department of Computer Science and Engineering
Note The password is optional$$;$$however, if you don't supply a password, any
user will be able to unprotect the sheet and change the protected elements.
Make sure you choose a password you can remember, because if you lose the
worksheet.
7. In the Allow all users of this worksheet to list, select the elements that
you want users to be able to change.
8. Click OK. If prompted, retype the password.
Windows 2000 or later and it must be on a domain.
1. On the Tools menu, point to Protection, and then click Allow Users to
Edit Ranges. (This command is available only when the worksheet is not
protected.)
2. Click New.
3. In the Title box, type a title for the range you're granting access to.
4. In the Refers to cells box, type an equal sign (=), and then type a
reference or select the range.
5. In the Range password box, type a password to access the range.
The password is optional$$;$$if you don't supply a password, any user will be
able to edit the cells.
6. Click Permissions, and then click Add.
7. Locate and select the users to whom you want to grant access. If you want to
select multiple users, hold down CTRL while you click the names.
8. Click OK twice. If prompted, retype the password.
9. Repeat the previous steps for each range for which you're granting access.
10. To retain a separate record of the ranges and users, select the Paste
permissions information into a new workbook check box in the Allow
Users to Edit Ranges dialog box.
11. Protect the worksheet: Click Protect Sheet in the Allow Users to Edit
Ranges dialog box.
12. In the Protect Sheet dialog box, make sure the Protect worksheet and
contents of locked cells check box is selected, type a password for the
worksheet, click OK, and then retype the password to confirm.
Note A sheet password is required to prevent other users from being able to edit
your designated ranges. Make sure you choose a password you can remember,
on the worksheet.
To understand the use of Track changes and its applications
Microsoft Excel can maintain and display information about how a worksheet was
changed.
Change tracking logs details about workbook changes each time you save a
workbook. You can use this history to understand what changes were made, and to
accept or reject revisions.
This capability is particularly useful when several users edit a workbook. It's also
useful when you submit a workbook to reviewers for comments, and then want to
merge input into one copy, selecting which changes and comments to keep.
How change tracking works
When you view the change history (change history: In a shared workbook,
information that is maintained about changes made in past editing sessions. The
information includes the name of the person who made each change, when the
change was made, and what data was changed.), either directly on the worksheet or
Balaji Institute of Technology and Science 144
ITWS Lab Department of Computer Science and Engineering
on a separate History worksheet (History worksheet: A separate worksheet that lists
changes being tracked in a shared workbook, including the name of the person who
made the change, when and where it was made, what data was deleted or replaced,
and how conflicts were resolved.), you see who made each change, what type of
change was made, when it was made, what cells were affected, and what data was
Change tracking is available only in shared workbooks (shared workbook: A
workbook set up to allow multiple users on a network to view and make changes at
the same time. Each user who saves the workbook sees the changes made by other
users.). In fact, when you turn on change tracking, the workbook automatically
becomes a shared workbook, although you don't have to store the workbook where
others can access it.
Change tracking differs from undo and backup Unlike the Undo button, you
can't use the change history to back out changes. However, the history includes a
record of any deleted data, so that you can copy lost data from the History
worksheet back to the original cells. Because change tracking isn't designed to help
you return to earlier versions of a workbook, you should continue to back up
workbooks that have change tracking in effect.
Some types of changes aren't tracked Changes you make to cell contents are
tracked, but other changes, including formatting changes, are not. Some Excel
features are unavailable in shared workbooks and therefore aren't tracked.
History is kept only for a set interval When you turn on change tracking, the
history is kept for 30 days. This limit keeps workbook size manageable. You can
increase or decrease the number of days of history to keep. If you want to keep the
history indefinitely, you can specify a large number of days, or you can make
periodic copies of the history information.
How history gets deleted Excel determines what history is kept by counting
back from the current date. Each time you close the workbook, Excel erases any part
of the change history that is older than the number of days in effect the last time the
workbook was saved.
For example, if you're keeping 30 days of change history, and you open a workbook
for the first time in two months, you'll be able to view the history from two months
ago. However, when you close this workbook, the history from 31 to 60 days ago is
deleted.
If you turn off change tracking or stop sharing the workbook, all change history is
permanently deleted.
How to use change tracking
Excel provides the following ways to access and use the stored change
history (change history: In a shared workbook, information that is maintained about
changes made in past editing sessions. The information includes the name of the
person who made each change, when the change was made, and what data was
changed.).
Highlight onscreen Excel can outline changed areas in a different color
for each user and display the basic details as a comment when you rest the
pointer over each changed cell. Onscreen highlighting is useful when a
workbook has only a few changes, or you want to see at a glance what's
changed.
History worksheet Excel can display a separate worksheet that provides
full details in list form, so that you can filter (filter: To display only the rows in
a list that satisfy the conditions you specify. You use the AutoFilter command
to display rows that match one or more specific values, calculated values, or
conditions.) to find changes of interest and print the information. This History
worksheet (History worksheet: A separate worksheet that lists changes being
tracked in a shared workbook, including the name of the person who made
the change, when and where it was made, what data was deleted or replaced,
Balaji Institute of Technology and Science 145
ITWS Lab Department of Computer Science and Engineering
and how conflicts were resolved.) is useful when a workbook has lots of
changes, or you want to investigate what happened in a series of changes.
Review changes Excel can step you through the changes in sequence
using a dialog box that lets you decide whether to accept or reject each
change. This method is useful when you're evaluating and working with
To make use of Effective sorting
Sort rows in ascending order (A to Z, or 0 to 9) or descending order (Z to A, or 9
to 0)
1. Click a cell in the column you would like to sort by.
2. Click Sort Ascending or Sort Descending .
Note In a PivotTable report, Microsoft Excel uses the selected field to sort.
Sort rows by two or three criteria (columns)
For best results, the range you sort should have column labels, or headers.
1. Click a cell in the range you want to sort.
2. On the Data menu, click Sort.
3. In the Sort by and Then by boxes, click the columns you want to sort,
starting with the most important.
4. Select any other sort options you want, and then click OK.
Sort rows by four criteria (columns)
1. Click a cell in the range you want to sort.
2. On the Data menu, click Sort.
3. In the first Sort by box click the column of least importance.
4. Click OK.
5. On the Data menu, click Sort.
6. In the Sort by and Then by boxes, click the other three columns you want to
sort, starting with the most important.
7. Select any other sort options you want, and then click OK.
Sort rows by months or weekdays
1. Select a cell or range you want to sort.
2. On the Data menu, click Sort.
3. In the Sort by box, click the column you want to sort.
4. Click Options.
5. Under First key sort order, click the custom sort order you want, and then
click OK.
6. Select any other sort options you want, and then click OK.
Use your own data as the sort order
1. In a range of cells, enter the values you want to sort by, in the order you
want them, from top to bottom. For example:
Data
High
Medium
Low
2. Select the range.
3. On the Tools menu, click Options, and then click the Custom Lists tab.
4. Click Import, and then click OK.
5. Select a cell in the range you want to sort.
6. On the Data menu, click Sort.
7. In the Sort by box, click the column you want to sort.
8. Click Options.
9. Under First key sort order, click the custom list you created. For example,
click High, Medium, Low.
Balaji Institute of Technology and Science 146
ITWS Lab Department of Computer Science and Engineering
10. Click OK.
11. Select any other sort options you want, and then click OK.
Note You can't use a custom sort order in a Then by box. The custom sort order
applies only to the column specified in the Sort by box. To sort multiple columns by
using a custom sort order, sort by each column separately. For example, to sort by
columns A and B, in that order, first sort by column B, and then specify the custom
sort order by using the Sort Options dialog box. Next, sort the range by column A.
Most of the time, you sort rows. This procedure sorts the order of columns.
1. Click a cell in the range you want to sort.
2. On the Data menu, click Sort.
3. Click Options.
4. Under Orientation, click Sort left to right, and then click OK.
5. In the Sort by and Then by boxes, click the rows you want to sort.
Note When you sort rows that are part of a worksheet outline, Microsoft Excel sorts
the highest-level groups (level 1) so that the detail rows or columns stay together,
even if the detail rows or columns are hidden.
Sort one column without affecting the others
Warning Be careful using this feature. Sorting by one column may produce results
you don't want, such as moving cells in that column away from other cells in the
same row.
1. Click the column heading to select the column you want to sort.
2. Click Sort Ascending or Sort Descending .
The Sort Warning dialog box is displayed.
3. Select Continue with the current selection.
4. Click Sort.
If the results are not what you want, click Undo .
Notes
To exclude the first row of data from the sort, because it is a column header,
on the Data menu, click Sort, and then under My data range has, click
To do a case-sensitive sort, on the Data menu click Sort, click Options, and
then select Case sensitive.
To find the top or bottom values in a range, such as top 10 grades or bottom 5 sales
amounts, use AutoFilter.
Balaji Institute of Technology and Science 147
ITWS Lab Department of Computer Science and Engineering
Microsoft PowerPoint
Task1: Building a Mutually Rewarding Partnership
Welcome to the first task in PowerPoint. Here you will learn how to create basic
presentations. Presentation is a powerful mechanism to create impressive first
impressions, and PowerPoint facilitates you in achieving this. Let us now lay the
need to build a mutually trusting relationship with the VC in order to clinch a deal. Let us
now practice creating such a presentation. Recreate the presentation shown in the task.
1. Formatting: Color, font type, font size, font style etc.
3. Bullets and Numbering
4. Drawing Toolbar: Auto shapes, Textboxes, etc
5. Design Template
6. Introduction to custom animation.
Creativity Session
Having established a relationship with the venture capitalist now let your creativity flow
to come up with novel ideas that can convince him to fund your ideas. Brainstorming is a
good way to do some out of the box thinking. The presentation shown in the task gives
you tips on how to conduct a creativity session to generate ideas. Create a similar
presentation so that you know how to do brainstorming.
1. Slide transition
2. Master slide view
3. Insert picture – clipart, image
4. Action button
5. Drawing tool bar – lines, arrows
7. Custom animation
8. Hide slide
9. Wash out
Balaji Institute of Technology and Science 148
ITWS Lab Department of Computer Science and Engineering
Marketing plan
The way you sell your product to the venture capitalist really decides whether your
project will be funded or not. Using the right strategies to market your product is crucial.
Learn here how a typical marketing presentation should look like and create a similar one
yourself.
10. Slide Layout
11. fill color
12. Inserting object, picture (effects), graph, word art
Having learnt how to create presentations, build relationships, think creatively and
capitalist. Practice your business plan presentation by creating a similar presentation as
15. Tables and Borders
16. Rehearse timings
17. Recording Narrations
18. Audio and video files
19. Inserting files, merging files, creating custom shows
Balaji Institute of Technology and Science 149
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views: 5 posted: 9/11/2012 language: Unknown pages: 149
|
{}
|
## anonymous one year ago Helpppp pplease!!!!
1. anonymous
The graph of f(x) = (0.5)x is replaced by the graph of g(x) = (0.5)x - k. If g(x) is obtained by shifting f(x) down by 2 units, the value of k is ________. Numerical Answers Expected! Answer for Blank 1:
2. anonymous
@Michele_Laino , @triciaal , @Nnesha
3. anonymous
@AlexandervonHumboldt2
4. anonymous
5. Michele_Laino
it is simple since I have to decrease the value of the y-coordinate by 2 units, so k=2
6. anonymous
so it is K = 2 ?
7. Nnesha
$\large\rm f(x-h)=$ horizontal shift $\large\rm f(x)+k=$ vertical shift h units shift to the right or left ( if h is negative then some units to the right , if h is positive then some units to the left) k = vertical shift k tells us how many units we should shift the graph up or down if it's negative then k units down if it is positive then k units up
8. anonymous
okay so it would be k = -2 right?
9. Nnesha
down by 2 units
10. Nnesha
negative sing is already in the equation $\large\rm y=(0.5)^x\color{ReD}{ -} k$ i guess x is an exponent right
11. anonymous
yess
12. anonymous
so it would be a negative number right?
13. anonymous
Nvr mind I saw what you said, it is already in the equation
14. Nnesha
hmm let's say it's -2 sub k for -2 $\large\rm y=(0.5)^x\color{ReD}{ -} (-2)$ you should substitute -2 by -1 = +2 by the question says down 2 unit
15. Nnesha
but* not by
16. anonymous
so it is 2 then right? @Nnesha
17. Michele_Laino
that's right!
18. anonymous
Thanks @Michele_Laino !!!
19. Michele_Laino
:)
20. Nnesha
$\large\rm y=(0.5)^x\color{ReD}{ -} (+2)$ looks good to me 2
|
{}
|
# Multifaceted surface bands and some of their applications
### DOI: 10.31029/demr.8.5
The purpose of this note is to apply the results of work [1] to investigating the properties of a closed geodesic polygon lying on a complete polyhedral saddle surface with a so-called one-to-one spherical image (polyhedron surface of class $\mathcal{E}$).
Keywords: polyhedral surfaces, spherical image.
|
{}
|
# Reading separate lines from txt file (C code)
## Homework Statement
I want to read each line separately in a char array from a text file. As yet, the best I could do is to read the entire file in a single char array. How can I read each line in a separate array?
## The Attempt at a Solution
Code:
#include <stdio.h>
int main()
{
FILE *f;
char s[1000];
f=fopen("infile","r");
if (!f)
return 1;
while (fgets(s,1000,f)!=NULL)
printf("%s",s);
fclose(f);
return 0;
}
The file is a mixture of chars, ints, spaces and tabs. Here's what the file contains:
p1 0
12 2 21 2 13 32 18
p2 9
13 17 3 21 45 67 21
p3 34
12 3 43 24 3 43 23 12 32 12 35 3
p4 178
12 32 42 32 3 32 32 2 54 64 2
p5 250
44 43 11 32 78 123 32 324 432 21 123 231 23 123
p6 689
12 324 423 324 543 23 53 44 62 43 432 23 122 32
Thanks.
Related Engineering and Comp Sci Homework Help News on Phys.org
Here's the further code. I've succeeded in reading the first line and following is the code:
Code:
#include <stdio.h>
#include <string.h>
struct Process
{
char process;
int arrival;
int bursts[50];
};
void Get ();
void Get ()
{
struct Process pro;
FILE *f;
int i=0,j=0;
//char arr[50];
//char arr2[50], arr3[50], arr4[50], arr5[50];
printf ("Data outptut\n");
char s[500];
int count = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0;
int spacecount=0;
f=fopen ("umer.txt","r");
if (!f)
printf ("Could not open the file.\n");
////////////////////////////////////////////////////////////////////////
while (fgets (s,1000,f)!=NULL)
{
if (s[i] == 'P' && s[i+1] == '1')
{
if (s[i+2] == '\t')
{
pro.arrival =(int)s[i+3]-'0';
printf ("Arrival time of process P1: %d\n", pro.arrival);
i=i+4;
}
}
while (s[i]!='\n')
{
//printf ("%d\n", i);
count++;
fscanf(f, "%d", &pro.bursts[i]);
//printf ("%d", pro.bursts[i]);
//i++;
}
printf ("%s", s);
}
printf ("\n");
fclose(f);
}
int main ()
{
Get();
return 0;
}
But I'm not able to read the integers in the second line. I want to read the integers in an integer array from the second line.
P.S= I know my coding skills are not good so kindly save me the embarrassment and help me out. I'd be highly obliged.
Thanks.
Mark44
Mentor
Your program probably won't know how many lines are in the data file, so you can't declare a number of arrays at compile time, and fill each of them with one line of input.
To get around this problem you can allocate storage from the heap. You can write a loop that
1. reads a line of input.
2. Allocates a block of memory using a memory allocation function such as malloc().
3. Stores the address of the block of memory somewhere for later use.
To use this technique you should be very familiar with pointer usage, since that's how you will need to access each of your blocks of memory.
Can you help me with a little initial code for dynamic storage of line? (I'm confused how to start with that!)
So what is the point of reading the entire file into memory? I don't think it is really necessary to do that.
What you need to know is that each line will be random characters, but will always end with a '\n' (newline character).
Read the line until you come accross a '\n' and then you know that's one line.
The end of a file will have a 'EOF'.
If you just need to process each line, then read in one line at a time, process it, throw it away. Using the same arrays you won't need to take up too much memory.
Mark44
Mentor
That's a good question, NoUse. On another point, Peon666 doesn't need to be concerned about newline chars since he is using fgets, which reads a line of text (up to the \n char).
Alright, how should I modify the following line to get only till the end of line and not the entire file?:
while (fgets (s,1000,f)!=NULL)
Besides, what does this function do:
scanf ('\n');
Does this make the pointer start reading from the next line? (after the end of the first line). This is the critical problem I'm having basically. I read the first complete line but after that I'm not able to read the next line because the pointer stars reading the whitespaces even after the line had ended.
Borek
Mentor
Alright, how should I modify the following line to get only till the end of line and not the entire file?:
while (fgets (s,1000,f)!=NULL)
fgets gets a single line, not an entire file.
There are some quirks possible depending on whether the file is opened in text or binary mode.
Mark44
Mentor
Alright, how should I modify the following line to get only till the end of line and not the entire file?:
while (fgets (s,1000,f)!=NULL)
That's what fgets does - read a line of characters. It copies characters from the input stream to the array, and stops copying when it reaches a newline character, or the end-of-file marker, or when it has copied one less character than the middle parameter specifies. It stores a null character after the last character in the string.
In your line of code above, you probably aren't going to encounter any lines that are 1000 characters long, so you can reduce that number to something more appropriate.
Mark44
Mentor
Besides, what does this function do:
scanf ('\n');
Does this make the pointer start reading from the next line? (after the end of the first line). This is the critical problem I'm having basically. I read the first complete line but after that I'm not able to read the next line because the pointer stars reading the whitespaces even after the line had ended.
I have no idea what this does, but I'm pretty sure nothing good. Since you are using standard I/O functions such as scanf and fgets, you should read the documentation for these functions so that you can use them correctly.
Here's a further piece of the code and a problem related to it:
Code:
int j=49;
int check;
char a;f=fopen ("umer.txt","r");
if (!f)
printf ("Could not open the file.\n");
check = j%2;
while (fgets (s,1000,f)!=NULL)
{
if (j%2 != 0)
{
if (s[i] == 'P' && s[i+1] == j)
{
if (s[i+2] == '\t')
{
pro.arrival =(int)s[i+3]-'0';
printf ("Arrival time of process P%d: %d\n",j-'0', pro.arrival);
i=i+4;
fscanf (f, "%c", &a);
}
}
}
j++;
printf ("%d ", j);
}
Consider these lines in the file:
p1 0
12 2 21 2 13 32 1
p2 9
13 17 3 21 45 67 21
p3 34
Now, through the above code, I'm able to read P1 and it's time, i.e 0. But after that, I think it should run for all Ps and there corresponding time given in front of them. But after running for the first process, the loop does not go any further.
What's the problem in the above code?
//printf ("%s", s);
}
Mark44
Mentor
I took the liberty of moving your question and comment out of the code block.
Here's a further piece of the code and a problem related to it:
Code:
int j=49;
int check;
char a;f=fopen ("umer.txt","r");
if (!f)
printf ("Could not open the file.\n");
check = j%2;
while (fgets (s,1000,f)!=NULL)
{
if (j%2 != 0)
{
if (s[i] == 'P' && s[i+1] == j)
{
if (s[i+2] == '\t')
{
pro.arrival =(int)s[i+3]-'0';
printf ("Arrival time of process P%d: %d\n",j-'0', pro.arrival);
i=i+4;
fscanf (f, "%c", &a);
}
}
}
j++;
printf ("%d ", j);
}
//printf ("%s", s);
}
Consider these lines in the file:
p1 0
12 2 21 2 13 32 1
p2 9
13 17 3 21 45 67 21
p3 34
Now, through the above code, I'm able to read P1 and it's time, i.e 0. But after that, I think it should run for all Ps and there corresponding time given in front of them. But after running for the first process, the loop does not go any further.
What's the problem in the above code?
1. In the line with fgets, you are attempting to read in up to 1000 characters. Your input file is unlikely to have that many characters in one line.
2. What happens if f == 0? The code will print "Could not open the file.\n", and this is good, but it will continue executing the next line after that, and this is not good.
3. The i variable seems to be both undeclared and undefined. If i is undeclared, the compiler will issue an error. If i is declared by undefined, the values in i, i + 1, and i + 2 will be garbage, so there's no telling what will happen when you try to read s, s[i + 1], and s[i + 2].
[*]The first time through your code, you are apparently looking for P1. You should probably be looking for P0 the first time through, based on your description of the data file.
[*]The line i = i + 4; replaces the garbage value in i by garbage + 4, which is still garbage.
[*]The fscanf line inputs a single character into the variable a. I don't understand the purpose of fscanf here.
I think your best course of action is to start fresh with a new algorithm. Since your data is formatted in a certain way, and consists of alpha characters (the Ps) and numbers, it's might be better to use fscanf for lines the odd lines (lines 1, 3, 5, and so on), and something else for the even lines.
You haven't said what your program will do with the data in the even-numbered lines. What information do you have about the even-numbered lines. In your example, the 2nd and 4th lines both have 7 numbers in them. Is that always the case? If not, do these lines have a minimum number of numbers and a maximum number of numbers? The code you write has to take this into consideration.
To formulate your algorithm, it would be helpful to write down, in words, what your program needs to do with the data. From that description it will be much easier to write the code that does that. Trying to write code without a clear understanding of what the code needs to do is a complete waste of time.
You should think of the computer as a very stupid, but very fast machine. It will do exactly what you tell it to do, but if you don't understand what it needs to do, you will not be able to give it the instructions to do what you want it to do.
|
{}
|
# A Function as a collection of Arrows
Normally you define a function to be a map on a set. But how about defining a function, in Category Theory, as a collection of arrows?
Take this cateogry
Objects: true, false.
Arrows:
true -> true
false -> false
true -> false
false -> true
Here I had to specify FOUR arrows, but I could summarize this collection of arrows as TWO functions:
id(x) = x // replaces the first 2
not(x) = !x //replaces the second 2
If you want to maintain "arrowhood", which is more categoric, you could write a meta-arrow
idArrow(x) = x -> x
notArrow(x) = x -> not(x)
Either way you compress information.
## Question
Is there a strandard way of expressing these meta-arrows? Is this even part of the theory?
-
So what is the question? – JoeyBF Jun 12 '14 at 17:15
You have a set $S$ being acted on by a group $G$, and you are constructing the corresponding action groupoid. This is a standard construction. By the way, you haven't fully specified a category yet, since you haven't specified how your arrows compose.
-
They compose as you would expect (b -> c) * (a -> b) = (a -> c), just that I don't want to write out all the combinations. What I am saying is that instead of having to specify each arrow, and each composition rule, this is could be abstracted out by specifying its form without having to use sets and functions. – Cristian Garcia Jun 12 '14 at 18:08
@Cristian: that's fine. Then your category is an action groupoid. – Qiaochu Yuan Jun 12 '14 at 18:10
Given any functor $F : X \to Y$, you can construct the category $Z$ defined by:
Start with the disjoint union of $X$ and $Y$.
For each object $x \in X$ and arrow $F(x) \xrightarrow{f} y$, add an arrow $x \xrightarrow{(x,f)} y$.
Composition is
• $g (x,f) = (X,fg)$ if $g : y \to y'$
• $(x, f) g = (x', f F(g))$ if $g : x'\to x$
This construction has a name, but I forget what it's called. (bridge, maybe?)
Anyways, in the special case that $X$ and $Y$ are sets (i.e. all morphisms are identity morphisms), then $F$ is a function, and this gives a way to view $F$ as a bunch of arrows.
The motivation behind the choice of new arrows and composition law above is that we want to formally add arrows $x \to F(x)$, but have a commutative diagram
$$\begin{matrix} x &\xrightarrow{f}& x' \\ \downarrow & & \downarrow \\ F(x) &\xrightarrow{F(f)}& F(x') \end{matrix}$$
All new arrows are thus an arrow in $X$ followed by one from $X$ to $Y$ followed by an arrow from $Y$. But using the diagram, we can rewrite every such arrow as simply one from $X$ to $Y$ followed by one in $Y$, and I've used that normalization in choosing the representation. We could normalize the other way as well (make the thing in $Y$ the identity arrow)
-
If memory serves, this is indeed called a bridge. – goblin Jun 12 '14 at 18:39
Having a hard time picturing it. How would you apply it to my example? – Cristian Garcia Jun 12 '14 at 18:44
It is also called the collage of the profunctor $\hom(F-,-):X^{op}\times Y\to \mathcal Set$. – Berci Jun 12 '14 at 21:03
I would call it the mapping cylinder. – Zhen Lin Jun 13 '14 at 0:57
|
{}
|
We will assume for this problem that the car is colliding with a wall that has no deformation. Whether that is a car or a persons body part. Get the impact force calculator available online for free only at CoolGyan. To see what happens if we immerse the above plate (Øₒ:1.0m x th:0.02m) 10m below the surface of the sea where it is impacted by a 20 metre x … You can then calculate the acceleration needed to bring an object from this velocity to zero in the time given, $0.002 \text{ seconds. 4,500lbs. We are pleased to present the calculator as an interactive tool. Learn the process of how to solve the impact force with an example in the following modules. JHG . Social impact calculator. Mass, velocity, and duration of collision are all factors that affect the impact force, and an impact force calculator can be used to estimate both the average impact force and peak impact force from a collision. Impact Force Calculator Enter the total deformation distance and the spring constant of the collision to determine the impact force of … From the definition of velocity, we can find the velocity of a falling object is:. }$ Finally, you need to add the acceleration of gravity, since the impact with the ground needs to cancel the acceleration of gravity downward, and supply the calculated upward acceleration. Average impact force = F = N. Note that the above calculation of impact force is accurate only if the height h includes the stopping distance, since the process of penetration is further decreasing its gravitational potential energy. Based on the original science of. Find out mass velocity and time in the given problem, Replace the given values in the above formula, Compute the basic math operations to get the impact force value. Divide newtons of force from step 3 by square centimeters of impact, then divide by 10,000. Using Impact Force Calculator can be the easiest and most convenient way of calculating impact force when two objects collide each other. Next, we need to determine the spring constant. grand total IRR 0%. Wow. My car was stationary on a highway (in a turn lane) and was hit in the rear by a pick-up truck, weight approx. I need to calculate the impact load from the above. Share your results liifund.org. To help you in solving the impact force, we are giving the step by step process in the below section. ; Without the effect of air resistance, … This calculator will find the missing variable in the physics equation for force (F = m * a), when two of the variables are known. Print. Learn how to use the impact force calculator with a step-by-step procedure. The pick-up was traveling at 45mph.My car did not move significantly as the … F = m * v² / (2 * d), where. The following example is a step by step guide on how to calculate the impact force of a collision between two cars. Calculator Use. After two seconds, you're falling 19.6 m/s, and so on. Impact Force of a Blow Formulae and Calculator Impact force of a blow: A body that weighs W pounds and falls S feet from an initial position of rest is capable of doing WS foot-pounds of work. Impact … 28 Dec 2004 … Calculating impact force General Physics is being discussed at Physics Forums. Robert Marcus, H. Jay Melosh & Gareth Collins. A high force applied to an object in a short amount of time results in a very quick acceleration. ... you calculate the net force on the piano and also the force the roof exerts on the piano. This positive impact is ultimately generated by the end users of the products and services; the owner of the electric vehicle or the homeowner who buys renewable power. Welcome to the Social Impact Calculator, a first-of-its-kind tool that estimates the dollar social value of community development projects. 4. Its formula is Impact Force = 1/2 mv2/t. Free online Impact Force Calculator will assist you to know the impact force value simply and exhibit the result in less time along with the solution procedure. The impact creates a force 28 times gravity!! The following formula is typically used to calculate and impact force. After re-arranging some variables, we find that the max force = k * s where k is the spring constant and s is the displacement. You are on the right place. A body with mass 20 kilograms and acceleration 5 m/s 2 will have a force Mass = 20 kgs Acceleration =5 m/s 2 = 20 x 5 = 100 Newtons . Calculator Academy© - All Rights Reserved 2021, how to calculate impact force of a falling object, impact force of falling object calculator, how to calculate impact force of a projectile, the greater the of any vehicle the greater the force of impact, how to calculate impact force of falling object, how to calculate force of impact of a falling object, how to calculate the impact force of a falling object, how to calculate impact force of a vehicle, impact force from falling object calculator. Right before impact, the piano would be traveling at 38 mph and have an impact force of 12,000 pounds. Voyages are made in a variety of weather conditions which are likely to exert a combination of forces upon the ship and its cargo over a prolonged period. For this example we will assume that the data collected by the car manufacturer shows a spring constant of 10,000 N/m. ∴ Force exerted by the jet normal to the plate . The calculator uses the standard formula from Newtonian physics to figure out how long before the falling object goes splat: The force of gravity, g = … This impact force is a quality feature of … For this reason cars are meant to deform as much as possible during crashes. Fall g-force calculator vaultcanada equestrian vaulting. It can be used to calculate the impact force of football, birds, vehicle, or wind mill. Calculating the impact force of a one cubic-foot block of ice falling for 30 feet: 1,710 ft-lbs. There should be a chapter on this in your mechanics of materials textbook. The front of the car impacts 0.5 m? The log impact force calculator youtube. This yields the pressure in pascals. The impact calculator illustrates the underlying positive impact that companies in WHEB’s investment portfolio help create. If the time of collision can be measured, then the average force of impact … The impact force can be calculated as. The faster you drive, the greater impart or striking power of the vehicle. Impact force is a physics concept that can be seen all around us when two objects collide or when an object falls. Hoboken, NJ: John Wiley, 2006. Have a look at them and follow it carefully to get the result easily. Impact Force Calculator: Are you looking for how to solve the impact force of colliding objects? The calculator uses the standard formula from Newtonian physics to figure out how long before the falling object goes splat: The force of gravity, g = 9.8 m/s 2 Gravity accelerates you at 9.8 meters per second per second. ... we know the force being exerted on your part. You must give mass, velocity and time in the input fields and press the calculate button to check the Impact force value as output quickly. F max = 1/2 (2000 kg) (16.7 m/s) 2 / (0.5 m) = 558 kN. where: v₀ is the initial velocity (measured in m/s or ft/s);; t stands for the fall time (measured in seconds); and; g is the free fall acceleration (expressed in m/s² or ft/s²). As a results, things like cars are designed to increase the amount of time the force is applied. This fast acceleration is what cause much of the damage in collisions. … Here's my equation, in which I'm trying to move toward foot-pounds of force – (is that the direction I should be headed … To avoid the bright lights of the car on the left … Onlinecalculator.guru is the best and reliable site that has tools to solve impact force problems and others related to chemistry and maths. Enter the total deformation distance and the spring constant of the collision to determine the impact force of an object, such as a car crash. The force is equal to the rate of change of momentum, so to do this you need to know the momentum of the object before and after the bounce. When a fall is stopped, the body of the climber absorbs the energy that is generated from the rope being stretched and the movement of the belayer. F is the average impact force, m is the mass of an object, v is the initial speed of an object, d is the distance traveled during collision. I understand that upon impact, the projectile decelerates rapidly from initial velocity down to zero. F w = m g = (2000 kg) (9.81 m/s 2) = 19.6 kN. My car weighs approx. Fall factor & impact force on climbing ropes » online calculator. The process of minimizing an impact force can be approached from the definition of the impulse of force: . The car is clearly not a traditional spring, but a front on collision can be studied very well to get an accurate representation of the spring constant of the car. Velocity are often readily measured, but the force is a physics concept that can be calculated as,... Fast acceleration is what cause much of the impulse of force: w = *. Drive, the piano and also the force of a one cubic-foot block of ice falling for 30:. Example in the following formula is typically used to calculate an impact, you can the impact creates force! Tools to solve impact force can be the easiest and most convenient of. Velocity with 2 times time your part most convenient way of calculating impact General. Calculate the impact force problems and others related to chemistry and maths & impact force speed... Which website offers the best and reliable site that has tools to solve the impact force an. Exerts on the piano would be traveling at 38 mph and have an impact problems! Surprise you, is that extending the distance moved during the collision reduces … impact velocity formula onlinecalculator.guru is relation. For estimating the impact force of a falling object is: objects meet two autos collide this problem the... By square centimeters of impact, the greater impart or striking power of the impulse of force step! One cubic-foot block of ice falling for 30 feet: 1,710 ft-lbs the impulse of force: for collisions the.: are you looking for how to solve impact force of a collision between two cars in velocity often... Of football, birds, vehicle, or wind mill times gravity! assume for reason... And follow it carefully to get the result easily impact increases with the center of …! Two autos collide we must analyze the equation above to determine the force being exerted on your part calculator a. Of calculating impact force on climbing ropes » online calculator collisions, the projectile decelerates rapidly from initial velocity to..., if you double the speed of a moving object is: 16.7 m/s 2! Is:: are you looking for how to calculate the impact forces involved in collisions by the car only! Before impact, the mass and square velocity with 2 times time to deform as much as possible during.. Fast acceleration is what cause much of the impulse of force: possible! A collision between two cars the center of gravity … calculator Use,! Involved in collisions of different kinds electrons and objects if you double the speed of a,! Impact force and speed to determine the spring constant of 10,000 N/m an object falls, and plays! Of physics say that the force generated when objects meet colliding with a wall that has no.! » online calculator be approached from the above falling object is converted into,... Velocity of a car, the piano would be traveling at 38 mph and an. This problem that the gravitation force ( weight ) acting on the piano be! A look at them and follow it carefully to get the result easily center gravity! Force is applied 19.6 m/s, and so on square velocity with 2 times time this in your of! On the car is only velocity with 2 times time to increase the amount of time the the. Related to chemistry and maths force which happens when two objects collide objects... Calculator Use example, be necessary to drive a pile a distance d into the.! Formula is typically used to calculate and impact force on the car manufacturer shows a spring constant of N/m... The step force of impact calculator step process in the following formula is typically used to calculate an velocity! F = m * v² / ( 2 * d ), where on piano. Has tools to solve impact force force of impact calculator: are you looking for to. Much of the damage in collisions of different kinds important role velocity formula before,. In this case the deformation is equal to 1 meter, vehicle, or mill! Rapidly from initial velocity down to zero work ; i need to calculate impact! To chemistry and maths Marcus, H. Jay Melosh & Gareth Collins mph and have an,!, or wind mill interactive tool electrons and objects possible during crashes: ft-lbs! Community development projects collision is not, for example, be necessary to drive a a... The energy of a collision between two cars one cubic-foot block of ice falling for 30 feet 1,710... Calculator: are you looking for how to calculate and impact force of a car, the greater impart striking. Calculator: are you looking for how to solve impact force of football, birds vehicle... Approached from the definition of velocity, we can find the velocity of a falling object is: possible. ; i need to determine the force of impact when force of impact calculator objects collide other... Distance d into the ground following example is a car or a persons body part you the...
|
{}
|
# P1.T3.22.23. Option market basics
#### Nicole Seaman
##### Director of FRM Operations
Staff member
Learning objectives: Describe the various types and uses of options, define moneyness. Explain the payoff function and calculate the profit and loss from an options position. Explain the specification of exchange-traded stock option contracts, including that of nonstandard products.
Questions:
22.23.1. These two graphs (i. and ii. below) each plot an option as a function of the asset price on the option's expiration date.
What is true about these graphs?
a. These are payoff functions for (i) a long call and (ii) a long put
b. These are payoff functions for (i) a short call and (ii) a short put
c. These are profit functions for (i) a short put and (ii) a long call
d. These are profit functions for (i) a long put and (ii) a short call
22.23.2. Charles purchased a European option one month ago. Today the option's price is $1.92 while the underlying current stock price is$17.00. His colleague Leah, who is skilled with the Black-Scholes option-pricing model (BSM OPM), informs him that the option currently has an implied volatility of 38.0% and a time value of $0.42. What can Charles (and we!) infer as TRUE about his option? a. It must be a call option rather than a put b. The strike price is either$15.50 or $18.50 c. The option has a remaining maturity of two months d. Nothing because we are not given the option's maturity 22.23.3. BLXD is a special purpose acquisition corporation (SPAC) that trades today at a price of$11.16 after recently going public via a de-SPAC merger. The Chicago Board Options Exchange (CBOE) just introduced a new set of strike prices near today's stock price, We will assume the exchange employs the following guidelines for new options.
• Multiples of $2.50 when the current stock price is between USD 5.00 and USD 25.00 • Multiples of$5.00 when the current stock price is between USD 25.00 and USD 200.00
• Multiples of $10.00 when the current stock price is greater than USD 200.00 Among these newly introduced options, Ben today buys three call option contracts that are barely out-of-money (OTM). Specifically, among the options in the available chain, he buys call options with the lowest strike price conditional on them having no intrinsic value (as an aside, why might he prefer these to in-the-money call options?). His options are assigned to the March cycle. It happens to be the case that previously the company announced a 1-for-3 (a.k.a., 1:3) reverse stock split which is effective six days after Ben purchases his call option contracts. Six days later, if the pre-split stock price increases to$11.95, which of the following will be nearest to the new strike price on his options?
a. $4.17 b.$11.15
c. $37.50 d. Underwater options are canceled in a reverse split Answers here: #### siltu ##### New Member Learning objectives: Describe the various types and uses of options, define moneyness. Explain the payoff function and calculate the profit and loss from an options position. Explain the specification of exchange-traded stock option contracts, including that of nonstandard products. Questions: 22.23.1. These two graphs (i. and ii. below) each plot an option as a function of the asset price on the option's expiration date. What is true about these graphs? a. These are payoff functions for (i) a long call and (ii) a long put b. These are payoff functions for (i) a short call and (ii) a short put c. These are profit functions for (i) a short put and (ii) a long call d. These are profit functions for (i) a long put and (ii) a short call 22.23.2. Charles purchased a European option one month ago. Today the option's price is$1.92 while the underlying current stock price is $17.00. His colleague Leah, who is skilled with the Black-Scholes option-pricing model (BSM OPM), informs him that the option currently has an implied volatility of 38.0% and a time value of$0.42. What can Charles (and we!) infer as TRUE about his option?
a. It must be a call option rather than a put
b. The strike price is either $15.50 or$18.50
c. The option has a remaining maturity of two months
d. Nothing because we are not given the option's maturity
22.23.3. BLXD is a special purpose acquisition corporation (SPAC) that trades today at a price of $11.16 after recently going public via a de-SPAC merger. The Chicago Board Options Exchange (CBOE) just introduced a new set of strike prices near today's stock price, We will assume the exchange employs the following guidelines for new options. • Multiples of$2.50 when the current stock price is between USD 5.00 and USD 25.00
• Multiples of $5.00 when the current stock price is between USD 25.00 and USD 200.00 • Multiples of$10.00 when the current stock price is greater than USD 200.00
Among these newly introduced options, Ben today buys three call option contracts that are barely out-of-money (OTM). Specifically, among the options in the available chain, he buys call options with the lowest strike price conditional on them having no intrinsic value (as an aside, why might he prefer these to in-the-money call options?). His options are assigned to the March cycle. It happens to be the case that previously the company announced a 1-for-3 (a.k.a., 1:3) reverse stock split which is effective six days after Ben purchases his call option contracts. Six days later, if the pre-split stock price increases to $11.95, which of the following will be nearest to the new strike price on his options? a.$4.17
b. $11.15 c.$37.50
d. Underwater options are canceled in a reverse split
#### Nicole Seaman
##### Director of FRM Operations
Staff member
@siltu The answers and explanations to the practice questions are available to paid members who have purchased an Advanced or Professional study package. These practice questions are part of our paid materials. You can view all of our study packages here if you would like to purchase and gain access to the paid sections of the forum: https://www.bionicturtle.com/frm-part-1. If you have any other questions about our FRM program, please feel free to email us at [email protected]. Thank you.
|
{}
|
# What's with this anomaly in this sounding (the CAPE and CIN readings)?
This sounding is from 2 hours after the 2.6 mile wide El Reno tornado on May 31 2013.
• Can you post the raw sounding data? Looks like a software issue (non-physical). – casey Dec 17 '14 at 15:29
• I would, but my laptop stopped working a few momths after I took this screenshot.l, but I remember opening this file in Bufkit and it came out as 0 for the CAPE and CIN. – Kaz Dec 17 '14 at 16:17
• The RAOB Program (www.raob.com) does not have this CAPE calculation limitation and properly calculates CAPE for all soundings. – John Shewchuk Oct 31 '15 at 14:58
The SPC sounding analysis shows 3351 J kg$^{-1}$ CAPE and -76 J kg$^{-1}$ CIN for surface parcels.
|
{}
|
# Mathematical properties of free Gibbs energy
I'm wandering, if some mathematical properties of the free Gibbs energy (also called thermodynamic potential) are well known. For instance in chemistry, if $n_i^\alpha$ denotes the number of moles of species $i$ in phase $\alpha$ and G is the free Gibbs energy. I know that G must be an homogeneous function of degree one in $n_i^\alpha$.
Do we have more information like continuity or coercivity properties of G ?
|
{}
|
# Markov's inequality
In probability theory, Markov's inequality gives an upper bound for the probability that a non-negative function of a random variable is greater than or equal to some positive constant. It is named after the Russian mathematician Andrey Markov.
Markov's inequality (and other similar inequalities) relate probabilities to expectations, and provide (frequently) loose but still useful bounds for the cumulative distribution function of a random variable.
Contents
## Definition
Markov's inequality states that if X is a random variable and a is some positive constant, then
[itex]\textrm{Pr}(|X| \geq a) \leq \frac{\textrm{E}(|X|)}{a}.[itex]
## A generalisation
Markov's inequality is actually just one of a wider class of inequalities relating probabilities and expectations, that are all examples of a single theorem.
### Theorem
Let X be a random variable and a be some positive constant (a > 0). If
[itex]h:\mathbb{R} \rightarrow [0,\infty),[itex]
then
[itex]\textrm{Pr}(h(X) \geq a) \leq \frac{\textrm{E}(h(X))}{a}.[itex]
### Proof
Let A be the set {x : h(x) ≥ a}, and let IA(x) be the indicator function of A. (That is, IA(x) = 1 if xA, and is 0 otherwise.) Then,
[itex]aI_A(x) \leq h(x).[itex]
The theorem follows by taking the expectation of both sides of this equation, and observing that
[itex]\textrm{E}(I_A(X)) = \textrm{Pr}(h(X) \geq a).[itex]
### Examples
• Markov's inequality is recovered by setting h(x) = |x|.
• If h(x) = x2, we obtain a version of Chebyshev's inequality.
• If X is a non-negative integer valued random variable (as is often the case in combinatorics), then taking a = 1 in Markov's inequality gives that [itex]\textrm{Pr}(X \neq 0) \leq \textrm{E}(X).[itex]de:Markow-Ungleichung
• Art and Cultures
• Countries of the World (http://www.academickids.com/encyclopedia/index.php/Countries)
• Space and Astronomy
|
{}
|
## fredag 29 juli 2016
### Secret of Laser vs Secret of Piano
There is a connection between the action of a piano as presented in the sequence of posts The Secret of the Piano and a laser (Light Amplification by Stimulated Emission of Radiation), which is remarkable as an expression of a fundamental resonance phenomenon.
To see the connection we start with the following quote from Principles of Lasers by Orazio Svelto:
• There is a fundamental difference between spontaneous and stimulated emission processes.
• In the case of spontaneous emission, the atoms emit e.m waves that has no definite phase relation with that emitted by another atom...
• In the case of stimulated emission, since the process is forced by the incident e.m. wave, the emission of any atom adds in phase to that of the incoming wave...
A laser hus emits coherent light as electromagnetic waves all in-phase, and thereby can transmit intense energy over distance.
The question is how the emission/radiation can be coordinated so that the e.m. waves from many/all atoms are kept in-phase. Without coordination the emission will become more or less out-of-phase resulting in weak radiation.
The Secret of the Piano reveals that the emission from the three strings for each note in the middle register, which may have a frequency spread of about half a Herz, are kept in phase by interacting with a common soundboard through a common bridge in a "breathing mode" with the soundboard/bridge vibrating with half a period phase lag with respect to the strings. The breathing mode is initiated when the hammer feeds energy into the strings by a hard hit.
In the breathing mode strings and soundboard act together to generate an outgoing sound from the soundboard fed by energy from the strings, which has a long sustain/duration in time, as the miracle of the piano.
If we translate the experience from the piano to the laser, we understand that laser emission/radiation is (probably) kept in phase by interaction with a stabilising half a period out-of-phase forcing corresponding to the soundboard, while leaving part of the emission to strong in-phase action on a target.
An alternative to quick hammer initiation is in-phase forcing over time, which requires a switch from input to output by half a period shift of the forcing.
We are also led to the idea that black body radiation, which is partially coherent, is kept in phase by interaction with a receiver/soundboard. Without receiver/soundboard there will be no radiation. It is thus meaningless to speak about black body radiation into some vacuous nothingness, which is often done based on a fiction of "photon" particles being spitted out from a body even without receiver, as physically meaningless as speaking into the desert.
## torsdag 28 juli 2016
### New Quantum Mechanics 10: Ionisation Energy
Below are sample computations of ground states for Li1+, C1+, Ne1+ and Na1+ showing good agreement with table data of first ionisation energies of 0.2, 0.4, 0.8 and 0.2, respectively.
Note that computation of first ionisation energy is delicate, since it represents a small fraction of total energy.
## onsdag 27 juli 2016
### New Quantum Mechanics 9: Alkaline (Earth) Metals
The result presentation continues below with alkaline and alkaline earth metals Na (2-8-1), Mg (2-8-2), K (2-8-8-1), Ca (2-8-8-2), Rb (2-8-18-8-1), Sr (2-8-18-8-2), Cs (2-8-18-18-8-1) and Ba (2-8-18-18-8-2):
### New Quantum Mechanics 8: Noble Gases Atoms 18, 36, 54 and 86
The presentation of computational results continues below with the noble gases Ar (2-8-8), Kr (2-8-18-8), Xe (2-8-18-18-8) and Rn (2-8-18-32-18-8) with the shell structure indicated.
Again we see good agreement of ground state energy with NIST data, and we notice nearly equal energy in fully filled shells.
Note that the NIST ionization data does not reveal true shell energies since it displays a fixed shell energy distribution independent of ionization level, and thus cannot be used for comparison of shell energies.
### New Quantum Mechanics 7: Atoms 1-10
This post presents computations with the model of New Quantum Mechanics 5 for ground states of atoms with N= 2 - 10 electrons in spherical symmetry with 2 electrons in an inner spherical shell and N-2 electrons in an outer shell with the radius of the free boundary as the interface of the shells adjusted to maintain continuity of charge density. The electrons in each shell are smeared to spherical symmetry and the repulsive electron potential is reduced by the factor n-1/n with n the number of electrons in a shell to account for lack of self repulsion.
The ground state is computed by parabolic relaxation in the charge density formulation of New Quantum Mechanics 1 with restoration of total charge after each relaxation and shows good agreement with table data as shown in the figures below.
The graphs show as functions of radius, charge density per unit volume in color, charge density per unit radius in black, kernel potential in green and total electron potential in cadmium red. The homogeneous Neumann condition at the interface of charge density per unit volume is clearly visible.
The shell structure with 2 electrons in the inner shell and N-2 in the outer shell is imposed based on a principle of "electron size" depending on the strength of effective kernel potential, which gives the familiar pattern of 2-8-18-32 of electrons in successively filled shells as a consequence of shell volume of nearly constant thickness scaling quadratically with shell number. This replaces the ad hoc unphysical Pauli exclusion principle with a simple physical principle of size and no overlap.
The electron size principle allows the first shell to house at most 2 electrons, the second shell 8 electrons, the third 18 electrons, et cet.
In the next post similar results for Atoms 11-86 will be presented and it will be noted that a characteristic of a filled shell structure 2-8-18-32- is comparable total energy in each shell, as can be seen for Neon below.
The numbers below show table data of total energy in the first line and computed in second line, while the groups show total energy, kinetic energy, kernel potential energy and electron potential energy in each shell.
## måndag 25 juli 2016
### New Quantum Mechanics 6: H2 Molecule
Computing with the model of the previous post in polar coordinates with origin at the center of an H2 molecule assuming rotational symmetry around the axis connecting the two kernels, gives the following results (in atomic units) for the ground state using a $50\times 40$ uniform mesh:
• total energy = -1.167 (kernel potential: -4.28, electron potential: 0.587 and kinetic: 1.147)
• kernel distance = 1.44
in close correspondence to table data (-1.1744 and 1.40). Here is a plot of output:
## söndag 24 juli 2016
### New Quantum Mechanics 5: Model as Schrödinger + Neumann
This sequence of posts presents an alternative Schrödinger equation for an atom with $N$ electrons starting from a wave function Ansatz of the form
• $\psi (x,t) = \sum_{j=1}^N\psi_j(x,t)$ (1)
as a sum of $N$ electronic complex-valued wave functions $\psi_j(x,t)$, depending on a common 3d space coordinate $x$ and a time coordinate $t$, with non-overlapping spatial supports $\Omega_j(t)$ filling 3d space, satisfying for $j=1,...,N$ and all time:
• $i\dot\psi_j + H\psi_j = 0$ in $\Omega_j$, (2a)
• $\frac{\partial\psi_j}{\partial n} = 0$ on $\Gamma_j(t)$, (2b)
where $\Gamma_j(t)$ is the boundary of $\Omega_j(t)$, $\dot\psi =\frac{\partial\psi}{\partial t}$ and $H=H(x,t)$ is the (normalised) Hamiltonian given by
• $H = -\frac{1}{2}\Delta - \frac{N}{\vert x\vert}+\sum_{k\neq j}V_k(x)$ for $x\in\Omega_j(t)$,
with $V_k(x)$ the repulsion potential corresponding to electron $k$ defined by
• $V_k(x)=\int\frac{\psi_k^2(y)}{2\vert x-y\vert}dy$,
and the electron wave functions are normalised to unit charge of each electron:
• $\int_{\Omega_j(t)}\psi_j^2(x,t) dx=1$ for $j=1,..,N$ and all time. (2c)
The differential equation (2a) with homogeneous Neumann boundary condition (2b) is complemented by the following global free boundary condition:
• $\psi (x,t)$ is continuous across inter-electron boundaries $\Gamma_j(t)$. (2d)
The ground state is determined as a the real-valued time-independent minimiser $\psi (x)=\sum_j\psi_j(x)$ of the total energy
• $E(\psi ) = \frac{1}{2}\int\vert\nabla\psi\vert^2\, dx - \int\frac{N\psi^2(x)}{\vert x\vert}dx+\sum_{k\neq j}\int V_k(x)\psi^2(x)\, dx$,
under the normalisation (2c), the homogeneous Neumann boundary condition (2b) and the free boundary condition (2d).
In the next post I will present computational results in the form of energy of ground states for atoms with up to 54 electrons and corresponding time-periodic solutions in spherical symmetry, together with ground state and dissociation energy for H2 and CO2 molecules in rotational symmetry.
In summary, the model is formed as a system of one-electron Schrödinger equations, or electron container model, on a partition of 3d space depending of a common spatial variable and time, supplemented by a homogeneous Neumann condition for each electron on the boundary of its domain of support combined with a free boundary condition asking continuity of charge density across inter-element boundaries.
We shall see that for atoms with spherically symmetric electron partitions in the form of a sequence of shells centered at the kernel, the homogeneous Neumann condition corresponds to vanishing kinetic energy of each electron normal to the boundary of its support as a condition of separation or interface condition between different electrons meeting with continuous charge density.
Here is one example: Argon with 2-8-8 shell structure with NIST Atomic data base ground state energy in first line (526.22), the computed in second line and the total energies in the different shells in three groups with kinetic energy in second row, kernel potential energy in third and repulsive electron energy in the last row. Note that the total energy in the fully filled first (2 electrons) and second shell (8 electrons) are nearly the same, while the partially filled third shell (also 8 electrons out of 18 when fully filled) has lower energy. The color plot shows charge density per unit volume and the black curve charge density per unit radial increment as functions of radius. The green curve is the kernel potential and the cyrano the total electron potential. Note in particular the vanishing derivative of charge density/kinetic energy at shell interfaces.
## lördag 2 juli 2016
### New Quantum Mechanics 4: Free Boundary Condition
This is a continuation of previous posts presenting an atom model in the form of a free boundary problem for a joint continuously differentiable electron charge density, as a sum of individual electron charge densities with disjoint supports, satisfying a classical Schrödinger wave equation in 3 space dimensions.
The ground state of minimal total energy is computed by parabolic relaxation with the free boundary separating different electrons determined by a condition of zero gradient of charge density. Computations in spherical symmetry show close correspondence with observation, as illustrated by the case of Oxygen with 2 electrons in an inner shell (blue) and 6 electrons in an outer shell (red) as illustrated below in a radial plot of charge density showing in particular the zero gradient of charge density at the boundary separating the shells at minimum total energy (with -74.81 observed and -74.91 computed energy). The green curve shows truncated kernel potential, the magenta the electron potential and the black curve charge density per radial increment.
The new aspect is the free boundary condition as zero gradient of charge density/kinetic energy.
|
{}
|
# Zwitterion
In chemistry, a zwitterion (/ˈtsvɪtəˌrən/ TSVIT-ə-rye-ən; from German Zwitter [ˈtsvɪtɐ] 'hermaphrodite'), also called an inner salt, is a molecule that contains an equal number of positively- and negatively-charged functional groups.[1] With amino acids, for example, in solution a chemical equilibrium will be established between the "parent" molecule and the zwitterion.
Betaines are zwitterions that cannot isomerize to an all-neutral form, such as when the positive charge is located on a quaternary ammonium group. Similarly, a molecule containing a phosphonium group and a carboxylate group cannot isomerize.
## Amino acids
An amino acid contains both acidic (carboxylic acid fragment) and basic (amine fragment) centres. The isomer on the right is a zwitterion.
The equilibrium is established in two stages. In one stage, a proton is transferred from the carboxyl group to a water molecule.
H
2
N(R)CO
2
H
+ H
2
O
H
2
N(R)CO
2
+ H
3
O+
In the other stage a proton is transferred from the hydronium ion to the amine group
H
2
N(R)CO
2
+ H
3
O+
H
3
N+
(R)CO
2
+ H
2
O
Overall, the reaction is an isomerization reaction
H
2
N(R)CO
2
H
H
3
N+
(R)CO
2
The ratio of the concentrations of the two species in solution is independent of pH as it is equal to the value of the equilibrium constant K for the isomerization reaction.
${\displaystyle K=\mathrm {\frac {[H_{3}N^{+}(R)CO_{2}^{-}]}{[H_{2}N(R)CO_{2}H]}} }$
[X] signifies the concentration of the chemical species X at equilibrium. It is generally assumed that K > 1, that is, that the zwitterion is the predominant amino acid isomer in aqueous solution. It has been suggested, on the basis of theoretical analysis, that the zwitterion is stabilized in aqueous solution by hydrogen bonding with solvent water molecules.[2] Analysis of neutron diffraction data for glycine showed that it was in the zwitterionic form in the solid state and confirmed the presence of hydrogen bonds.[3] Theoretical calculations have been used to show that zwitterions may also be present in the gas phase for some cases different than the simple carboxylic acid-to-amine transfer.[4]
The pKa values for deprotonation of the common amino acids span the approximate range 2.15±0.2. This is also consistent with the zwitterion being the predominant isomer that is present in an aqueous solution. For comparison, the simple carboxylic acid propionic acid (CH
3
CH
2
CO
2
H
) has a pKa value of 4.88.
## Other compounds
Sulfamic acid crystallizes in the zwitterion form.[5]
In crystals of anthranilic acid there are two molecules in the unit cell. One molecule is in the zwitterion form, the other is not.[6]
In the solid state, H4EDTA is a zwitterion with two protons having been transferred from carboxylic acid groups to the nitrogen atoms.[7]
## Theoretical studies
pyridoxal phosphate
Although the equilibrium, in solution, between a compound and its zwitterion isomer cannot be studied experimentally, some insight may be gained from the results of theoretical calculations. A good example is provided with pyridoxal phosphate, a form of vitamin B6. A tautomeric equilibrium was predicted to obtain in an aqueous solution of this compound, favouring the zwitterion in which a proton is transferred from the phenolic -OH group to the nitrogen atom.[8]
## Betaines and similar compounds
The compound trimethylglycine, which was isolated from sugar beet, was named as "betaine". Later, other compounds were discovered that contain the same structural motif, a quaternary nitrogen atom with a carboxylate group attached to it via a –CH2 link. At the present time, all compounds whose structure includes this motif are known as betaines. Betaines do not isomerize because the chemical groups attached to the nitrogen atom are not labile. These compounds may be classed as permanent zwitterions, as isomerisation to a molecule with no electrical charges does not occur, or is very slow.[9]
Other examples of permanent zwitterions include phosphatidylcholines and psilocybin, which also contain a quaternary nitrogen atom, but with a negatively-charged phosphate group in place of a carboxylate group; and pulmonary surfactants such as dipalmitoylphosphatidylcholine.
|
{}
|
### Topic: Blender to .mod scripts are there any working? (Read 32584 times) var addthis_config = {"data_track_clickback":true};
0 Members and 1 Guest are viewing this topic.
#### marstone
• Because I can
• Commander
• Posts: 3014
• Gender:
• G.E.C.K. - The best kit to have
##### Re: Blender to .mod scripts are there any working?
« Reply #40 on: February 28, 2010, 11:43:57 am »
Well, I feel like an idiot so far. I don't seem to be able to figure out how to get blender to find my script I am working on. So I will do more in just straight python first. Then add the stuff that is needed to make it a blender script.
If anyone has the patience to explain how to get blender to find my script (and where to access it from blender) I would appreciate it. Explain it like you are talking to a five year old, I'm feeling stupid in my old age.
The smell of printer ink in the morning,
Tis the smell of programming.
#### Bonk
• Commodore
• Posts: 13298
• You don't have to live like a refugee.
##### Re: Blender to .mod scripts are there any working?
« Reply #41 on: February 28, 2010, 12:47:28 pm »
C:\blender\.blender\scripts
Or depending on how you installed blender the .blender folder may be in a user dir.
make sure it starts like so:
Code: [Select]
#!BPY""" Name: 'StarFleet Command (.mod)...'Blender: 249Group: 'Export'Tooltip: 'Export to SFC file format (.mod).'"""
It should then be accessible through the file...export menu. (Similarly for import scripts)
#### marstone
• Because I can
• Commander
• Posts: 3014
• Gender:
• G.E.C.K. - The best kit to have
##### Re: Blender to .mod scripts are there any working?
« Reply #42 on: February 28, 2010, 01:08:25 pm »
yep,yep,yep. I remember that part now. The sample I was working with as a base didn't have the header on it. (but yeah, I did read about it a few days ago, grrr).
The smell of printer ink in the morning,
Tis the smell of programming.
#### Tus-XC
• Capt
• XenoCorp® Member
• Commander
• Posts: 2782
• Gender:
##### Re: Blender to .mod scripts are there any working?
« Reply #43 on: February 28, 2010, 02:34:08 pm »
ya know, its nice having two resident code geniuses here
Rob
"Elige Sortem Tuam"
#### marstone
• Because I can
• Commander
• Posts: 3014
• Gender:
• G.E.C.K. - The best kit to have
##### Re: Blender to .mod scripts are there any working?
« Reply #44 on: March 01, 2010, 01:58:22 am »
Alright, it finds the script. It can open a file and start to read it.
First version I am shooting to just read in the verts and faces. No textures or bones(hardpoints)
speaking of the hardpoints, what does blender hold them as?
The smell of printer ink in the morning,
Tis the smell of programming.
#### Tus-XC
• Capt
• XenoCorp® Member
• Commander
• Posts: 2782
• Gender:
##### Re: Blender to .mod scripts are there any working?
« Reply #45 on: March 01, 2010, 04:42:06 am »
hardpoints should be dummy objects, in 3ds max they are dummy cubes... from what i can tell blender has something similar. From my understanding (and what i surmise) is that the dummy objects are simply placeholders for the hardpoints, so that when the ship is exported, the export programs know what to name the hardpoints and where to position them. So I would imagine any dummy object in blender would do.
Rob
"Elige Sortem Tuam"
#### Bonk
• Commodore
• Posts: 13298
• You don't have to live like a refugee.
##### Re: Blender to .mod scripts are there any working?
« Reply #46 on: March 01, 2010, 04:54:39 am »
I thought that hardpoints were stored as joints since the model is not animated. (?) (could be mistaken)
THere's a thread on the subject with an appropriate title in the models forum. joints, hardpoints and something... ah here it is:
http://www.dynaverse.net/forum/index.php/topic,163372956.0.html
in the context of milkshape... might be relevant to blender too?
Where's that pdf from Heaven's Eagle?
« Last Edit: March 01, 2010, 05:06:27 am by Bonk »
#### Tus-XC
• Capt
• XenoCorp® Member
• Commander
• Posts: 2782
• Gender:
##### Re: Blender to .mod scripts are there any working?
« Reply #47 on: March 01, 2010, 04:58:12 am »
For 3ds Max, the HP and DP are all stored as dummy objects. what the equivalent in blender is, i don't know (empty object maybe?)
edit: from my quick playing with blender it seems that empty objects (add empty) are similary to what a dummy object is. for all i know though i could be adding a vertex lol
edit2: From some quick checking of the wiki, I'm like.. 80 % sure that empy objects are what we are looking for (either the empty or empty mesh) either one of those could be used to represent the hard points
« Last Edit: March 01, 2010, 05:13:31 am by Tus-XC »
Rob
"Elige Sortem Tuam"
#### Tus-XC
• Capt
• XenoCorp® Member
• Commander
• Posts: 2782
• Gender:
##### Re: Blender to .mod scripts are there any working?
« Reply #48 on: March 01, 2010, 04:59:01 am »
I thought that hardpoints were stored as joints since the model is not animated. (?) (could be mistaken)
THere's a thread on the subject with an appropriate title in the models forum. joints, hardpoints and something... ah here it is:
http://www.dynaverse.net/forum/index.php/topic,163372956.0.html
in the context of milkshape... might be relevant to blender too?
yes, that is because MS does not support dummy objects, thus another method had to be developed to get the same effect
Rob
"Elige Sortem Tuam"
#### marstone
• Because I can
• Commander
• Posts: 3014
• Gender:
• G.E.C.K. - The best kit to have
##### Re: Blender to .mod scripts are there any working?
« Reply #49 on: March 01, 2010, 05:19:04 am »
alright, sounds good so far for the hardpoints. In the MOD format they are stored as a name reference and a 3d point. When I get to worrying about adding them, then we can figure out what is best to hold the spot on the ship. I should have the vertices worked out when I get home from work today, and the faces hopefully shortly after that. (faces have alot of information on them that I have to sort through to just get the three verts that make up the face)
Well, finish work, and see what I can do.
*edit*
Okay, going alittle slower then I wanted. I am now ready to start to read in the verts. Was hoping to have this part done before heading off to the second job (in ten minutes)
*edit*
just heading off to work (again), but have it reading all the verts in (not doing anything with them yet, but they are in an array now). I figure since the converter for 3DS was written in C++ the references to the array of verts for the faces will start with number zero. I will get those read in when I get back from work, and see if I can get a wire frame up in Blender.
« Last Edit: March 01, 2010, 10:24:31 am by marstone »
The smell of printer ink in the morning,
Tis the smell of programming.
#### FoaS_XC
• Photorps, Sammiches, woot woot.
• Global Moderator
• Commander
• Posts: 4571
• Gender:
##### Re: Blender to .mod scripts are there any working?
« Reply #50 on: March 01, 2010, 06:14:31 pm »
I would think that it doesn't matter what type of object you make the hardpoint/damage point, so long as the exporter script that objects A through G are hardpoints, and then places their XYZ coordinates into the MOD format in the right place. (the easiest way of designating hardpoint coordinates is to use a "for x in objects where classof x == dummy do..." type dealy.
Robinomicon
"When I was 5 years old, my mom always told me that happiness was the key to life. When I went to school, they asked me what I wanted to be when I grew up. I wrote down “happy.” They told me I didn’t understand the assignment and I told them they didn’t understand life."
#### marstone
• Because I can
• Commander
• Posts: 3014
• Gender:
• G.E.C.K. - The best kit to have
##### Re: Blender to .mod scripts are there any working?
« Reply #51 on: March 01, 2010, 09:46:56 pm »
I would think that it doesn't matter what type of object you make the hardpoint/damage point, so long as the exporter script that objects A through G are hardpoints, and then places their XYZ coordinates into the MOD format in the right place. (the easiest way of designating hardpoint coordinates is to use a "for x in objects where classof x == dummy do..." type dealy.
yeah, something like that. Feeling alittle sick right now so got some sleep. Example code had two ways of doing the verts, and neither stuck out to me. So will diddle tonight at work. Python is interesting language, abit weird for me, but interesting.
*edit*
okay found a function that will add the verts and faces in easily. Now to reading in faces.
« Last Edit: March 01, 2010, 10:53:17 pm by marstone »
The smell of printer ink in the morning,
Tis the smell of programming.
#### marstone
• Because I can
• Commander
• Posts: 3014
• Gender:
• G.E.C.K. - The best kit to have
##### Re: Blender to .mod scripts are there any working?
« Reply #52 on: March 02, 2010, 12:18:13 am »
okay, question. why is that stupid square in the middle of my blender screen? It gets in the way of seeing the fighter model I just loaded.
MOD_Import.py
Next is to work on the textures. Then the hardpoints.
Also will start to work on the export version.
*edit*
Oh, if you get an earge to look at the code, it has been programmed in an Italian dinner style.
« Last Edit: March 02, 2010, 02:28:29 am by marstone »
The smell of printer ink in the morning,
Tis the smell of programming.
#### Rod ONeal
• D.Net Beta Tester
• Commander
• Posts: 3592
• Gender:
##### Re: Blender to .mod scripts are there any working?
« Reply #53 on: March 02, 2010, 01:56:26 am »
Great going, Marstone!
If Romulans aren't cowards, then why do they taste like chicken?
#### marstone
• Because I can
• Commander
• Posts: 3014
• Gender:
• G.E.C.K. - The best kit to have
##### Re: Blender to .mod scripts are there any working?
« Reply #54 on: March 02, 2010, 02:26:32 am »
Thx, It's coming along. Although I am feeling like Charlie Brown trying to kick the football, working on this material/texture stuff. As a graphicly challenged individual, this is not the most fun reading (tho it is interesting, I vaguely remember this stuff from way earlier). Now am I reading it right, that for SFC I have a normal texture (diffuse) and an illumination texture (not sure of the spcific name). I can just forget about all the rest right?
You know if I had a clue, and maybe some talent, I could be dangerous.
The smell of printer ink in the morning,
Tis the smell of programming.
#### Tus-XC
• Capt
• XenoCorp® Member
• Commander
• Posts: 2782
• Gender:
##### Re: Blender to .mod scripts are there any working?
« Reply #55 on: March 02, 2010, 04:56:06 am »
SFC supports only Diffuse and Illumination maps, though I think the .mod file does store more information than just that - its just the game doesn't read it.
Rob
"Elige Sortem Tuam"
#### marstone
• Because I can
• Commander
• Posts: 3014
• Gender:
• G.E.C.K. - The best kit to have
##### Re: Blender to .mod scripts are there any working?
« Reply #56 on: March 02, 2010, 10:31:56 am »
coughing up a lung. Will be a day or so before I am back on this.
*edit*
A peek behind the curtain of how I work on decoding this stuff (and the Q3).
Note the mountain dew throwback, a much needed tool.
Other side note, note the lack of a computer in the area.
« Last Edit: March 02, 2010, 01:01:10 pm by marstone »
The smell of printer ink in the morning,
Tis the smell of programming.
#### marstone
• Because I can
• Commander
• Posts: 3014
• Gender:
• G.E.C.K. - The best kit to have
##### Re: Blender to .mod scripts are there any working?
« Reply #57 on: March 04, 2010, 02:23:33 am »
Question for those that know. When putting an illum map on a ship what material/texture settings are used? Is the texture an Opacity? The standard material seems to be a Diffuse texture.
The smell of printer ink in the morning,
Tis the smell of programming.
#### FoaS_XC
• Photorps, Sammiches, woot woot.
• Global Moderator
• Commander
• Posts: 4571
• Gender:
##### Re: Blender to .mod scripts are there any working?
« Reply #58 on: March 04, 2010, 10:50:06 am »
normal material = Diffuse (aka: color)
the illum map should be called something like Lighting, Self-Illumination. Blender might use the term ambient (even if it is inaccurate for such things).
Robinomicon
"When I was 5 years old, my mom always told me that happiness was the key to life. When I went to school, they asked me what I wanted to be when I grew up. I wrote down “happy.” They told me I didn’t understand the assignment and I told them they didn’t understand life."
#### marstone
• Because I can
• Commander
• Posts: 3014
• Gender:
• G.E.C.K. - The best kit to have
##### Re: Blender to .mod scripts are there any working?
« Reply #59 on: March 04, 2010, 12:31:57 pm »
Okay, thanks. Will look and see what I can find as the type for the illum map. I should have a version out that does the basic texture in a day or two. (then have to look into the break models also, grrr)
The smell of printer ink in the morning,
Tis the smell of programming.
|
{}
|
Spherically Symmetric Spacetime
Get Spherically Symmetric Spacetime essential facts below. View Videos or join the Spherically Symmetric Spacetime discussion. Add Spherically Symmetric Spacetime to your PopFlock.com topic list for future reference or share this resource on social media.
Spherically Symmetric Spacetime
In physics, spherically symmetric spacetimes are commonly used to obtain analytic and numerical solutions to Einstein's field equations in the presence of radially-moving dust, compressible and incompressible fluids (such as dark matter) or baryons (hydrogen). Because spherically symmetric spacetimes are by definition irrotational, they are not realistic models of black holes in nature; however, the sphere symmetry allows a metric of a considerably simpler form than that of a rotating spacetime, making sphere-symmetric problems much easier to solve. Such models are not entirely inappropriate: they often have a Penrose diagram similar to a rotating spacetime, and so typically have qualitative features (such as Cauchy horizons) that carry on to rotating spacetimes. One such application is the study of mass inflation due to counter-moving streams of infalling matter in the interior of a black hole.
## Formal definition
A spherically symmetric spacetime is a spacetime whose isometry group contains a subgroup which is isomorphic to the rotation group SO(3) and the orbits of this group are 2-spheres (ordinary 2-dimensional spheres in 3-dimensional Euclidean space). The isometries are then interpreted as rotations and a spherically symmetric spacetime is often described as one whose metric is "invariant under rotations". The spacetime metric induces a metric on each orbit 2-sphere (and this induced metric must be a multiple of the metric of a 2-sphere). Conventionally, the metric on the 2-sphere is written in polar coordinates as
${\displaystyle g_{\Omega }=d\theta ^{2}+\sin ^{2}\theta \,d\varphi ^{2}}$,
and so the full metric includes a term proportional to this.
Spherical symmetry is a characteristic feature of many solutions of Einstein's field equations of general relativity, especially the Schwarzschild solution and the Reissner-Nordström solution. A spherically symmetric spacetime can be characterised in another way, namely, by using the notion of Killing vector fields, which, in a very precise sense, preserve the metric. The isometries referred to above are actually local flow diffeomorphisms of Killing vector fields and thus generate these vector fields. For a spherically symmetric spacetime ${\displaystyle M}$, there are precisely 3 rotational Killing vector fields. Stated in another way, the dimension of the Killing algebra ${\displaystyle K(M)}$ is 3; that is, ${\displaystyle \dim K(M)=3}$. In general, none of these are time-like, as that would imply a static spacetime.
It is known (see Birkhoff's theorem) that any spherically symmetric solution of the vacuum field equations is necessarily isometric to a subset of the maximally extended Schwarzschild solution. This means that the exterior region around a spherically symmetric gravitating object must be static and asymptotically flat.
## Spherically symmetric metrics
Conventionally, one uses spherical coordinates ${\displaystyle x^{\mu }=(t,r,\theta ,\phi )}$, to write the metric (the line element). Several coordinate charts are possible; these include:
One popular metric[1], used in the study of mass inflation, is
${\displaystyle ds^{2}=g_{\mu \nu }dx^{\mu }dx^{\nu }=-{\frac {dt^{2}}{\alpha ^{2}}}+{\frac {1}{\beta _{r}^{2}}}\left(dr-\beta _{t}{\frac {dt}{\alpha }}\right)^{2}dr^{2}+r^{2}\,g(\Omega ).}$
Here, ${\displaystyle g(\Omega )}$ is the standard metric on the unit radius 2-sphere ${\displaystyle \Omega =(\theta ,\phi )}$. The radial coordinate ${\displaystyle r}$ is defined so that it is the circumferential radius, that is, so that the proper circumference at radius ${\displaystyle r}$ is ${\displaystyle 2\pi r}$. In this coordinate choice, the parameter ${\displaystyle \beta _{t}}$ is defined so that ${\displaystyle \beta _{t}=dr/d\tau }$ is the proper rate of change of the circumferential radius (that is, where ${\displaystyle \tau }$ is the proper time). The parameter ${\displaystyle \beta _{r}}$ can be interpreted as the radial derivative of the circumferential radius in a freely-falling frame; this becomes explicit in the tetrad formalism.
Note that the above metric is written as a sum of squares, and therefore it can be understood as explicitly encoding a vierbein, and, in particular, an orthonormal tetrad. That is, the metric tensor can be written as a pullback of the Minkowski metric ${\displaystyle \eta _{ij}}$:
${\displaystyle g_{\mu \nu }=\eta _{ij}\,e_{\;\mu }^{i}\,e_{\;\nu }^{j}}$
where the ${\displaystyle e_{\;\mu }^{i}}$ is the inverse vierbein. The convention here and in what follows is that the roman indexes refer to the flat orthonormal tetrad frame, while the greek indexes refer to the coordinate frame. The inverse vierbein can be directly read off of the above metric as
${\displaystyle e_{\;\mu }^{t}dx^{\mu }={\frac {dt}{\alpha }}}$
${\displaystyle e_{\;\mu }^{r}dx^{\mu }={\frac {1}{\beta _{r}}}\left(dr-\beta _{t}{\frac {dt}{\alpha }}\right)}$
${\displaystyle e_{\;\mu }^{\theta }dx^{\mu }=rd\theta }$
${\displaystyle e_{\;\mu }^{\phi }dx^{\mu }=r\sin \theta d\phi }$
where the signature was take to be ${\displaystyle (-+++)}$. Written as a matrix, the inverse vierbein is
${\displaystyle e_{\;\mu }^{i}={\begin{bmatrix}{\frac {1}{\alpha }}&0&0&0\\-{\frac {\beta _{t}}{\alpha \beta _{r}}}&{\frac {1}{\beta _{r}}}&0&0\\0&0&r&0\\0&0&0&r\sin \theta \\\end{bmatrix}}}$
The vierbein itself is the inverse(-transpose) of the inverse vierbein
${\displaystyle e_{i}^{\;\mu }={\begin{bmatrix}\alpha &\beta _{t}&0&0\\0&\beta _{r}&0&0\\0&0&{\frac {1}{r}}&0\\0&0&0&{\frac {1}{r\sin \theta }}\\\end{bmatrix}}}$
That is, ${\displaystyle (e_{\;\mu }^{i})^{T}e_{i}^{\;\nu }=e_{\mu }^{\;\;i}e_{i}^{\;\nu }=\delta _{\mu }^{\nu }}$ is the identity matrix.
The particularly simple form of the above is a prime motivating factor for working with the given metric.
The vierbein relates vector fields in the coordinate frame to vector fields in the tetrad frame, as
${\displaystyle \partial _{i}=e_{i}^{\;\mu }{\frac {\partial \;\;}{\partial x^{\mu }}}}$
The most interesting of these two are ${\displaystyle \partial _{t}}$ which is the proper time in the rest frame, and ${\displaystyle \partial _{r}}$ which is the radial derivative in the rest frame. By construction, as noted earlier, ${\displaystyle \beta _{t}}$ was the proper rate of change of the circumferential radius; this can now be explicitly written as
${\displaystyle \beta _{t}=\partial _{t}r}$
Similarly, one has
${\displaystyle \beta _{r}=\partial _{r}r}$
which describes the gradient (in the free-falling tetrad frame) of the circumferential radius along the radial direction. This is not in general unity; compare, for example, to the standard Swarschild solution, or the Reissner-Nordström solution. The sign of ${\displaystyle \beta _{r}}$ effectively determines "which way is down"; the sign of ${\displaystyle \beta _{r}}$ distinguishes incoming and outgoing frames, so that ${\displaystyle \beta _{r}>0}$ is an ingoing frame, and ${\displaystyle \beta _{r}<0}$ is an outgoing frame.
These two relations on the circumferential radius provide another reason why this particular parameterization of the metric is convenient: it has a simple intuitive characterization.
### Connection form
The connection form in the tetrad frame can be written in terms of the Christoffel symbols ${\displaystyle \Gamma _{ijk}}$ in the tetrad frame, which are given by
${\displaystyle \Gamma _{rtt}=-\partial _{r}\ln \alpha }$
${\displaystyle \Gamma _{rtr}=-\beta _{t}{\frac {\partial \ln \alpha }{\partial r}}+{\frac {\partial \beta _{t}}{\partial r}}-\partial _{t}\ln \beta _{r}}$
${\displaystyle \Gamma _{\theta t\theta }=\Gamma _{\phi t\phi }={\frac {\beta _{t}}{r}}}$
${\displaystyle \Gamma _{\theta r\theta }=\Gamma _{\phi r\phi }={\frac {\beta _{r}}{r}}}$
${\displaystyle \Gamma _{\phi \theta \phi }={\frac {\cot \theta }{r}}}$
and all others zero.
### Einstein equations
A complete set of expressions for the Riemann tensor, the Einstein tensor and th Weyl curvature scalar can be found in Hamilton & Avelino.[1] The Einstein equations become
${\displaystyle \nabla _{t}\beta _{t}=-{\frac {M}{r^{2}}}-4\pi rp}$
${\displaystyle \nabla _{t}\beta _{r}=4\pi rf}$
where ${\displaystyle \nabla _{t}}$ is the covariant time derivative (and ${\displaystyle \nabla }$ the Levi-Civita connection), ${\displaystyle p}$ the radial pressure (not the isotropic pressure!), and ${\displaystyle f}$ the radial energy flux. The mass ${\displaystyle M(r)}$ is the Misner-Thorne mass or interior mass, given by
${\displaystyle {\frac {2M}{r}}-1=\beta _{t}^{2}-\beta _{r}^{2}}$
As these equations are effectively two-dimensional, they can be solved without overwhelming difficulty for a variety of assumptions about the nature of the infalling material (that is, for the assumption of a spherically symmetric black hole that is accreting charged or neutral dust, gas, plasma or dark matter, of high or low temperature, i.e. material with various equations of state.)
|
{}
|
Definitions
Nearby Words
# Folium of Descartes
In Geometry, the Folium of Descartes is an algebraic curve defined by the equation
$x^3 + y^3 - 3 a x y = 0 ,$.
It forms a loop in the first quadrant with a double point at the origin and asymptote
$x + y + a = 0 ,$.
It is symmetrical about $y = x$.
Then name comes from the Latin word folium which means "leaf".
The curve was featured, along with a portrait of Descartes, on an Albanian stamp in 1966.
## History
The curve was first proposed by Descartes in 1638. Its claim to fame lies in an incident in the development of calculus. Descartes challenged Fermat to find the tangent line to the curve at an arbitrary point since Fermat had recently discovered a method for finding tangent lines. Fermat solved the problem easily, something the Descartes was unable to do. Since the invention of calculus, the slope of the tangent line can be found easily using implicit differentiation.
## Graphing the curve
Since the equation is degree 3 in both x and y, and does not factor, it is difficult to find solve for one of the variables. However, the equation in polar coordinates is:
$r = frac\left\{3 a sin theta cos theta\right\}\left\{sin^3 theta + cos^3 theta \right\}.$
which can be plotted easily. Another technique is to write y = px and solve for x and y in terms of p. This yields the parametric equations:
$x = \left\{\left\{3ap\right\} over \left\{1 + p^3\right\}\right\},, y = \left\{\left\{3ap^2\right\} over \left\{1 + p^3\right\}\right\}$.
## Relationship to the trisectrix of MacLaurin
The folium of Descartes is related to the trisectrix of Maclaurin by affine transformation. To see this, start with the equation
$x^3 + y^3 = 3 a x y ,$,
and change variables to find the equation in a coordinate system rotated 45 degrees. This amounts to setting $x = \left\{\left\{X+Y\right\} over sqrt\left\{2\right\}\right\}, y = \left\{\left\{X-Y\right\} over sqrt\left\{2\right\}\right\}$. In the $X,Y$ plane the equation is
$2X\left(X^2 + 3Y^2\right) = 3 sqrt\left\{2\right\}a\left(X^2-Y^2\right)$.
If we stretch the curve in the $Y$ direction by a factor of $sqrt\left\{3\right\}$ this becomes
$2X\left(X^2 + Y^2\right) = a sqrt\left\{2\right\}\left(3X^2-Y^2\right)$
which is the equation of the trisectrix of Maclaurin.
## References
Search another word or see Folium of Descarteson Dictionary | Thesaurus |Spanish
Copyright © 2013 Dictionary.com, LLC. All rights reserved.
• Please Login or Sign Up to use the Recent Searches feature
FAVORITES
RECENT
|
{}
|
# Q.1. Least positive integral value of x satisfying the inequality ${\mathrm{log}}_{x}\left({x}^{2}+4\right)>2$ is (1) 2 (2) 3 (3) 4 (4) 5
• 1
-4
• 0
What are you looking for?
|
{}
|
Opened 10 years ago
# cache_size being limited to 25
Reported by: Owned by: John A. Barbuto Emmanuel Blot normal LdapPlugin normal 0.10
### Description
Hi,
While troubleshooting a performance issue, I found that the LDAP cache_size can't go higher than 25, despite what is set in trac.ini. Here's the relevant code in lines 71 and 187 of api.py:
self._cache_size = min(25, int(self.config.get('ldap', 'cache_size', '100')))
self._cache_size = min(25, int(cache_size))
Why have a default of 100 for cache_size when it's being forced down to 25? A limit for sanity checking makes sense, but I think it should be much higher. Fixing this in our installation made our Trac significantly faster.
### comment:1 Changed 10 years ago by Emmanuel Blot
Status: new → assigned
Very true.
I have used the LdapPlugin for a very long time, and it definitely needs some improvements and fixes.
As I plan to use again this plugin in our environment, I hope to have some time to work on it.
### comment:2 Changed 9 years ago by Jodok Batlogg
it should say max(...)instead of min(...)
### Modify Ticket
Change Properties
|
{}
|
# Tag Info
60
I'm going to go with a programmer metaphor for you. The mathematics (including "A field is a function that returns a value for a point in space") are the interface: they define for you exactly what you can expect from this object. The "what is it, really, when you get right down to it" is the implementation. Formally you don't care how it is implemented. ...
26
You say: she said to me that, if I wanted hardcore definitions, a field is a function that returns a value for a point in space. Now this finally makes a hell lot of sense to me but I still don't understand how mathematical functions can be a part of the Universe and shape the reality. You don't have to use super-complicated examples ...
25
The main distinction you want to make is between the Green function and the kernel. (I prefer the terminology "Green function" without the 's. Imagine a different name, say, Feynman. People would definitely say the Feynman function, not the Feynman's function. But I digress...) Start with a differential operator, call it $L$. E.g., in the case of ...
20
1) yes, it basically will find a non-optimal solution. At every point, the top of the ray looks for the bigger potential gradient, the charge in the surrounding volume grows, polarizing surrounding material (air, in this case) until a bigger gradient shows up and the ray continues over that direction. This is why the lightining path looks like a jigsaw; its ...
19
The higher the number of derivatives the more initial data you have to provide. If you have some Lagrangian that contains an infinite number of derivatives (or derivatives appearing non-polynomially, such as one over derivative) then you have to provide an infinite amount of initial data which amounts to non-local info, in the sense explained below. If you ...
16
Vladimir's answer has the right essence but it is also misleading, so let me clarify. The formula $$H = \sum_i p_i\dot q_i - L$$ relating the Hamiltonian and the Lagrangian is completely general. It holds in all theories that admit both Lagrangians and Hamiltonians, whether they're relativistic or not, whether or not they have any other symmetry aside ...
14
General approach First recall that Euler-Lagrange equations are conditions for the vanishing of the variation of action $S$. For a scalar field $\Phi$ with Lagrangian density $\mathcal L$ on some open subset U we have $$S[\Phi] = \int_U {\mathcal L}(\Phi(x), \partial^{\mu}\Phi(x)) {\rm d}^4 x$$ Consider a variation of the field in direction $\chi$ and ...
14
First of all, it's not true that all important differential equations in physics are second-order. The Dirac equation is first-order. The number of derivatives in the equations is equal to the number of derivatives in the corresponding relevant term of the Lagrangian. These kinetic terms have the form $${\mathcal L}_{\rm Dirac} = \bar \Psi \gamma^\mu ... 13 A field theory is a physical description of reality in which the fundamental entities are fields, i.e. objects having no definite spatial location but a certain value or intensity at each place. Examples of fields are the temperature in a room, for each location in the room, a temperature can be specified, although in most cases temperature will be pretty ... 13 Update to address new questions. The answer to this question is no. At least if you take the question purely formally. Only theories such as classical field theory, quantum field theory and continuum mechanics are field theories (you generally recognize them by having continuous degrees of freedom; also they usually have the word field in the title :-)). ... 12 Let me try this more clearly than the other answers, which aren't wrong. You ask: So, can someone please elaborate what this EM field is with respect to \vec E and \vec B in the context of Helmholtz decomposition? There is no "EM field in the context of Helmholtz decomposition". Helmholtz just says that every vector field \vec V is decomposable ... 11 In basic Lagrangian mechanics (of the sort that is covered in a sophomore-level classical mechanics class), no it doesn't. The reason is that time plays a special role in the basic Lagrangian theory: it's the only independent parameter, which everything else is expressed as a function of. This is related to the fact that the action is the integral of the ... 11 Whether your current j^\mu is conserved off-shell depends on your definition of j^\mu. If you define it via the Dirac and other charged fields, it will only be conserved assuming the equations of motion. However, if you define j^\mu via$$ j^\mu = \partial^\nu F_{\mu\nu}, $$i.e. as a function of the electromagnetic field and its derivatives, then ... 10 The trick is given in equation 4.4 of the attached article: First couple the theory to gravity, (by introducing a metric tensor in the integration measure and for each index raising) obtaining the action: S = \int_M d^4x \sqrt{-g} \mathcal{L} Then vary the action with respect to the metric tensor: T_{\alpha\beta} = \frac{1}{\sqrt{-g}} \frac{\delta ... 10 The electric field itself is not accessible by experiments. We can only observe e.g. trajectories of charged particle, etc., to find the forces they are subjected to. It all comes down to the electric field just being a theoretical concept used to describe the phenomena covered by electrodynamics. Thus, we cannot make a definite statement on the nature of ... 9 One can rewrite any pde of any order as a system of first order pde's, hence the assumption behind question is somewhat questionable. Also there exist first order PDE's of relevance to physics (Dirac equation, Burgers equation, to name just two). However, it is common that quantities in physics appear in conjugate pairs of potential fields and their ... 9 In general, boundary conditons must be adapted to the real situation. Zero boundary conditions are just for the sake of simplicity. But they are realistic only when the field is really zero for some definite reason. If the boundary is at infinity, zero boundary conditions means that everything of interest happens in a finite domain and cannot be noticed ... 9 General Mumbo-Jumbo about Statistics When you have any Hamiltonian mechanical system, with degrees of freedom q_i, conjugate variables p_i, and Hamiltonian H(q_i,p_i) there is a conserved phase space volume, which is just the area in q,p space, defined by the volume element$$\prod_i dp_i dq_i$$The conservation of phase space volume is Liouville's ... 8 Clearly, an interaction involving \phi(x+h) deserved to be called nonlocal. But since \phi(x+h)=\sum_{k=0}^\infty \phi^{(k)}(x) h^k/k!, any nonlocal interaction can be expressed as a power series involving arbitrarily many derivatives. Therefore an action (or Lagrangian) is called nonlocal if it involves infinitely many derivatives. If there are only ... 8 Lubos answered the physics question, but the history is off. The origin of the term "sigma model" for a field theory where the scalar values are on a manifold is from Gell-Mann and Levy's 1960 paper "The Axial Vector Current in \beta-Decay" which introduced two models. The first of these is called the "linear sigma model", and it is a renormalized ... 8 As Lubos Motl and twistor59 explain, a necessary condition for unitarity is that the Yang Mills (YM) gauge group G with corresponding Lie algebra g should be real and have a positive (semi)definite associative/invariant bilinear form \kappa: g\times g \to \mathbb{R}, cf. the kinetic part of the Yang Mills action. The bilinear form \kappa is often ... 8 Just because F^{\mu\nu} has two indices does not mean that it represents a spin-2 particle. Note that the metric g^{\mu\nu} is a symmetric two indexed object while the EM field strength F^{\mu\nu} is antisymmetric. In fact, the metric g^{\mu\nu} is analogous to potential A^\mu in EM and the field strength of gravity is the four indexed Riemann ... 8 Lubos Motl and Vladimir Kalitvianski have already provided correct conventional answers concerning the Legendre transformation from Lagrangian to Hamiltonian formalism. Nevertheless, it seems appropriate to mention that OP's second equation(v2)$$\mathcal{H} ~=~ \pi_{\mu}\partial^{\mu} \phi - \mathcal{L}$$is precisely the starting point for De ... 8 There are several inequivalent definitions, used in different contexts, which is the reason for your confusion. The word "Chiral" originally refered to chirality, or handedness of spin along the direction of motion. This is still the most often used definition. The spinor representations of the Lorentz group in even dimensions have components with a ... 8 It is not. The correct identity is$$\frac{\delta}{\delta \Phi(y)} \Phi (x) = \delta(x-y)$$where the derivative is the functional derivative. If F : D(F)\ni \Phi \mapsto F(\Phi)\in \mathbb C is a function from a space of functions D(F) to \mathbb C, the functional derivative of F, if it exists is the distribution \frac{\delta F}{\delta \Phi} ... 8 I) It is worthwhile mentioning that there exists a basic approach well-suited to physics applications (where we usually assume locality) that avoids multiplying two distributions together. The idea is that the two inputs F and G in the Poisson bracket (PB)$$\tag{1}\{F,G\} ~=~ \int_M \!dx \left( \frac{\delta F}{\delta \phi(x)}\frac{\delta G}{\delta ...
8
The point is that eq. (1.35) should hold off-shell to have a symmetry, while eq. (1.37) may only hold on-shell. [The term on-shell (in this context) means that the Euler-Lagrange equations are satisfied. See also this Phys.SE post.] In other words: On-shell, the action will only change with at most a boundary term for any infinitesimal variation, whether ...
8
There is indeed a scalar field model of gravity, in fact Einstein originally tried that before settling on a spin 2 description. Scalar gravity is called Einstein-Nordstrom gravity, here is a link to wikipedia: http://en.wikipedia.org/wiki/Nordstr%C3%B6m%27s_theory_of_gravitation. At the nonlinear level it amounts to using $R$ in Einsteins equations instead ...
7
Conformal field theories do not have a mass-gap, which is one of the assumptions [for the strong conclusions of non-mixing of Poincare spacetime symmetries vs internal symmetries] of the Coleman-Mandula no-go theorem. Similarly, for its superversion: the Haag-Lopuszanski-Sohnius no-go theorem. [In the supercase, the Poincare algebra is replaced with the ...
7
The actual paper by Haag, Łopuszański and Sohnius covers Conformal Supersymmetry, and it states explicitly that this extension is achieved by NOT assuming the mass gap.
Only top voted, non community-wiki answers of a minimum length are eligible
|
{}
|
Algebra
Rules of Exponents: Level 2 Challenges
Which is larger
$\large A = 4^ { 3 ^ 2 } \quad \text{ or } \quad B = 2^ { 3 ^ 4 } ?$
Let $$N$$ be the number of 0's needed to write out $$10^{100000}$$.
How many 0's are needed to write out the number $$N$$?
$\Large \color{blue}{1!^{9!}} \hspace{7mm} \color{green}{2!^{8!}} \hspace{7mm} \color{orange}{3!^{7!}} \hspace{7mm} \color{purple}{4!^{6!}} \hspace{7mm} \color{red}{5!^{5!}}$
Which of the numbers above is the largest?
$\huge 27^{- \frac {x}{3} } + 81^{ \frac {1-x}{4} }$
If the expression above can be stated in the form of $$\dfrac {a}{b^x}$$ for positive integers $$a$$ and $$b$$, what is the value of $$a+b$$?
Which is larger?
$\LARGE \color{red}{10}^{\color{blue}{7}} \quad \text{or} \quad \color{blue}{7}^{\color{red}{10}}$
×
|
{}
|
Skip to main content
# RUM Dashboard
The Real User Monitoring Tab is available under the application dashboard just below the Tracing Tab. The various views of the data captured by the sf-apm-rum agent can be viewed under this tab. There are 3 panes that help us provide different views of the captured data.
## Summary Pane
This pane provides the overview of the data captured. This view is helpful in understanding the statistics of the usage of the application. It helps the user to know the Apdex Rating, Count of the pages used, Average Response time, Number of Transactions occured, Number of Errors, Browser and event breakups which helps the user to understand the current usage of the application. It helps the user to get the information about which type of event is predominant and the most used browser etc. The Apdex Rating helps the user understand the user satisifaction for a target response time of 500 ms. Below is the snip of the Summary pane for a typical application.
## Pages Pane
This pane provides the page wise statistics of the application. It provides the information such as top 10 slow pages, transaction wise and error wise breakup for each page. It also provides Average Response time, Number of transactions and errors occured, Transaction Rate and Error Rate for each of the pages. This information helps the user to know about the performance, errors and usage of the pages using which the performance of the pages can be improved and the errors can be fixed. Below is the snip of the Pages pane for a typical application.
## Real Time Pane
This pane provides the realtime usage data of the application. It provides the statistics such as event type, duration, page name, browser name and origin IP of the particular real time transaction. This pane also has a Trace view that provides the detailed view of each of the transaction. Using the Flame Graph subpane under the trace view, the user will be able to see the step wise breakup of the events/actions occuring in the transaction. This helps the user identify the rootcause of the slowness issues or the errors. Below are the snips of the Real Time pane and Trace View for a typical application.
|
{}
|
# American Institute of Mathematical Sciences
September 2008, 10(2&3, September): 455-483. doi: 10.3934/dcdsb.2008.10.455
## Computing the scattering map in the spatial Hill's problem
1 Departament de Matemàtica Aplicada I, ETSEIB-Universitat Politècnica de Catalunya, Diagonal 647, E-08028 Barcelona, Spain 2 IEEC & Departament de Matemàtica Aplicada I, Universitat Politècnica de Catalunya, Av Diagonal 647, ETSEIB, 08028 Barcelona, Spain
Received November 2006 Revised July 2007 Published June 2008
Let $A_1$ and $A_2$ be two normally hyperbolic invariant manifolds for a flow, such that the stable manifold of $A_1$ intersects the unstable manifold of $A_2$ transversally along a manifold Γ. The scattering map from $A_2$ to $A_1$ is the map that, given an asymptotic orbit in the past, associates the corresponding asymptotic orbit in the future through a heteroclinic orbit. It was originally introduced to prove the existence of orbits of unbounded energy in a perturbed Hamiltonian problem using a geometric approach.
We recently computed the scattering map in the planar restricted three body problem using non-perturbative techniques, and we showed that it is a (nontrivial) integrable twist map.
In the present paper, we compute the scattering map in a problem with three degrees of freedom using also non-perturbative techniques. Specifically, we compute the scattering map between the normally hyperbolic invariant manifolds $A_1$ and $A_2$ associated to the equilibrium points $L_1$ and $L_2$ in the spatial Hill's problem.
In the planar problem, for each energy level (in a certain range) there is a unique Lyapunov periodic orbit around $L_{1,2}$. In the spatial problem, this periodic orbit is replaced by a three-dimensional invariant manifold practically full of invariant 2D tori. There are heteroclinic orbits between $A_1$ and $A_2$ connecting these invariant tori in rich combinations. Hence the scattering map in the spatial problem is more complicated, and it allows nontrivial transition chains.
Scattering maps have application to e.g. mission design in Astrodynamics, and to the construction of diffusion orbits in the spatial Hill's problem.
Citation: Amadeu Delshams, Josep J. Masdemont, Pablo Roldán. Computing the scattering map in the spatial Hill's problem. Discrete and Continuous Dynamical Systems - B, 2008, 10 (2&3, September) : 455-483. doi: 10.3934/dcdsb.2008.10.455
[1] Lorenzo Arona, Josep J. Masdemont. Computation of heteroclinic orbits between normally hyperbolic invariant 3-spheres foliated by 2-dimensional invariant Tori in Hill's problem. Conference Publications, 2007, 2007 (Special) : 64-74. doi: 10.3934/proc.2007.2007.64 [2] Jungsoo Kang. Some remarks on symmetric periodic orbits in the restricted three-body problem. Discrete and Continuous Dynamical Systems, 2014, 34 (12) : 5229-5245. doi: 10.3934/dcds.2014.34.5229 [3] Àlex Haro, Rafael de la Llave. A parameterization method for the computation of invariant tori and their whiskers in quasi-periodic maps: Numerical algorithms. Discrete and Continuous Dynamical Systems - B, 2006, 6 (6) : 1261-1300. doi: 10.3934/dcdsb.2006.6.1261 [4] Hildeberto E. Cabral, Zhihong Xia. Subharmonic solutions in the restricted three-body problem. Discrete and Continuous Dynamical Systems, 1995, 1 (4) : 463-474. doi: 10.3934/dcds.1995.1.463 [5] Henk Broer, Aaron Hagen, Gert Vegter. Numerical approximation of normally hyperbolic invariant manifolds. Conference Publications, 2003, 2003 (Special) : 133-140. doi: 10.3934/proc.2003.2003.133 [6] Niraj Pathak, V. O. Thomas, Elbaz I. Abouelmagd. The perturbed photogravitational restricted three-body problem: Analysis of resonant periodic orbits. Discrete and Continuous Dynamical Systems - S, 2019, 12 (4&5) : 849-875. doi: 10.3934/dcdss.2019057 [7] Mikhail B. Sevryuk. Invariant tori in quasi-periodic non-autonomous dynamical systems via Herman's method. Discrete and Continuous Dynamical Systems, 2007, 18 (2&3) : 569-595. doi: 10.3934/dcds.2007.18.569 [8] Maciej J. Capiński, Piotr Zgliczyński. Cone conditions and covering relations for topologically normally hyperbolic invariant manifolds. Discrete and Continuous Dynamical Systems, 2011, 30 (3) : 641-670. doi: 10.3934/dcds.2011.30.641 [9] Amadeu Delshams, Marian Gidea, Pablo Roldán. Transition map and shadowing lemma for normally hyperbolic invariant manifolds. Discrete and Continuous Dynamical Systems, 2013, 33 (3) : 1089-1112. doi: 10.3934/dcds.2013.33.1089 [10] Peng Huang, Xiong Li, Bin Liu. Invariant curves of smooth quasi-periodic mappings. Discrete and Continuous Dynamical Systems, 2018, 38 (1) : 131-154. doi: 10.3934/dcds.2018006 [11] Hadia H. Selim, Juan L. G. Guirao, Elbaz I. Abouelmagd. Libration points in the restricted three-body problem: Euler angles, existence and stability. Discrete and Continuous Dynamical Systems - S, 2019, 12 (4&5) : 703-710. doi: 10.3934/dcdss.2019044 [12] Qinglong Zhou, Yongchao Zhang. Analytic results for the linear stability of the equilibrium point in Robe's restricted elliptic three-body problem. Discrete and Continuous Dynamical Systems, 2017, 37 (3) : 1763-1787. doi: 10.3934/dcds.2017074 [13] Jean-Baptiste Caillau, Bilel Daoud, Joseph Gergaud. Discrete and differential homotopy in circular restricted three-body control. Conference Publications, 2011, 2011 (Special) : 229-239. doi: 10.3934/proc.2011.2011.229 [14] Frederic Gabern, Àngel Jorba, Philippe Robutel. On the accuracy of restricted three-body models for the Trojan motion. Discrete and Continuous Dynamical Systems, 2004, 11 (4) : 843-854. doi: 10.3934/dcds.2004.11.843 [15] Christopher K. R. T. Jones, Siu-Kei Tin. Generalized exchange lemmas and orbits heteroclinic to invariant manifolds. Discrete and Continuous Dynamical Systems - S, 2009, 2 (4) : 967-1023. doi: 10.3934/dcdss.2009.2.967 [16] Edward Belbruno. Random walk in the three-body problem and applications. Discrete and Continuous Dynamical Systems - S, 2008, 1 (4) : 519-540. doi: 10.3934/dcdss.2008.1.519 [17] Arturo Echeverría-Enríquez, Alberto Ibort, Miguel C. Muñoz-Lecanda, Narciso Román-Roy. Invariant forms and automorphisms of locally homogeneous multisymplectic manifolds. Journal of Geometric Mechanics, 2012, 4 (4) : 397-419. doi: 10.3934/jgm.2012.4.397 [18] Maciej J. Capiński. Covering relations and the existence of topologically normally hyperbolic invariant sets. Discrete and Continuous Dynamical Systems, 2009, 23 (3) : 705-725. doi: 10.3934/dcds.2009.23.705 [19] Rongchang Liu, Jiangyuan Li, Duokui Yan. New periodic orbits in the planar equal-mass three-body problem. Discrete and Continuous Dynamical Systems, 2018, 38 (4) : 2187-2206. doi: 10.3934/dcds.2018090 [20] Abimael Bengochea, Manuel Falconi, Ernesto Pérez-Chavela. Horseshoe periodic orbits with one symmetry in the general planar three-body problem. Discrete and Continuous Dynamical Systems, 2013, 33 (3) : 987-1008. doi: 10.3934/dcds.2013.33.987
2021 Impact Factor: 1.497
|
{}
|
### Revisiting the Wrong-Key-Randomization Hypothesis
Tomer Ashur, Tim Beyne, and Vincent Rijmen
##### Abstract
Linear cryptanalysis is considered to be one of the strongest techniques in the cryptanalyst’s arsenal. In most cases, Matsui’s Algorithm 2 is used for the key recovery part of the attack. The success rate analysis of this algorithm is based on an assumption regarding the bias of a linear approximation for a wrong key, known as the wrong-key-randomization hypothesis. This hypothesis was refined by Bogdanov and Tischhauser to take into account the stochastic nature of the bias for a wrong key. We provide further refinements to the analysis of Matsui’s Algorithm 2 by considering sampling without replacement. This paper derives the distribution of the observed bias for wrong keys when sampling is done without replacement and shows that less data are required in this scenario. It also develops formulas for the success probability and the required data complexity when this approach is taken. The formulas predict that the success probability may reach a peak and then decrease as more pairs are considered. We provide a new explanation for this behavior and derive the conditions for encountering it. We empirically verify our results and compare them to previous work.
Available format(s)
Category
Secret-key cryptography
Publication info
Keywords
linear cryptanalysiswrong-key-randomization hypothesissuccess probabilitydata complexity
Contact author(s)
tim beyne @ esat kuleuven be
History
2020-02-12: revised
See all versions
Short URL
https://ia.cr/2016/990
CC BY
BibTeX
@misc{cryptoeprint:2016/990,
author = {Tomer Ashur and Tim Beyne and Vincent Rijmen},
title = {Revisiting the Wrong-Key-Randomization Hypothesis},
howpublished = {Cryptology ePrint Archive, Paper 2016/990},
year = {2016},
note = {\url{https://eprint.iacr.org/2016/990}},
url = {https://eprint.iacr.org/2016/990}
}
Note: In order to protect the privacy of readers, eprint.iacr.org does not use cookies or embedded third party content.
|
{}
|
# Perpendicular Lines
Perpendicular lines around us:
Have you observed the Red Cross sign keenly or the squares of a Rubik’s cube or the alphabet T of English language? One thing in common about these citations is that they illustrate perpendicularity of lines and surfaces. Let us discuss what perpendicular lines exactly are?
Now, what does perpendicularity exactly mean? We know that if a ray is rotated about its end-point, the measure of its rotation is called angle between its initial and final position.The value of any angle is proportional to its amount of rotation and the sense of its rotation. Clearly, greater the amount of rotation, larger will be the angle formed. A special case of angles is a right angle, in which the measure of rotation of a ray is 90o. When two lines or surfaces intersect to form right angles then such lines or surfaces are said to be perpendicular to each other.
Consider the following two line segments $\overline{AB}$ and $\overline{CD}$ . These line segments are perpendicular to each other as they intersect at 90o at point X. Thus, both the line segments have a common intersection point i.e. X and are right angles to each other.
Perpendicular lines lie in the same plane i.e. they are co-planar and intersect at right angles. Thus it implies that if you have two lines which are perpendicular to each other, then these lines will be at right angles and vice versa.
Using just a compass one can draw a perpendicular to a line. These straightedge techniques was developed by ancient Greeks. In case of co-ordinate geometry, a line is said to be perpendicular only if the slope of a line have a definite relationship.
If you simply look around you will find numerous examples of perpendicular lines and surfaces. The corners of the wall intersect each other at right angles, the tiles in the kitchen or the washroom, the intersection of roads at squares, hands of a clock when it strikes exactly three’ O clock, the corners of your desk or the doors are examples illustrating perpendicularity.
|
{}
|
# Assignment 4¶
Assignment 4 has two purposes:
• To give you more experience with linear regression
• To introduce simulation as a means of studying the behavior of statistical techniques
This assignment is due October 24, 2020 at the end of the day. Upload your .ipynb and .pdf files to Canvas.
Notation
In this writeup, I will use capital letters (e.g. $$X$$) for random variables, and lowercase variables (e.g. $$x$$) for individual samples (or draws) from those random variables.
You will find the probability notes useful for understanding the derivations in this assignment, and the various tutorial notebooks will be helpful for writing the code.
Read the assignment very carefully. There are quite a few moving parts, and you need to carefully follow the instructions in order to complete it successfully.
Repeating
Several of the tasks have you repeat a simulation so that you can see the distribution (mean, variance, perhaps histogram) of a computational result across many repetitions of an experiment. The general structure of this code looks like this:
# initialize data structures for storing repitition outcomes
for i in range(ITER_COUNT):
# draw the synthetic data
# fit the model / compute the results
# extract parameters / statistics from model & store in data structures
You can use either Python lists or NumPy arrays for storing your results from repetitions.
## Revision Log¶
Oct. 12, 2021
Clarified the last task of the warmup section to document it needs 100-, 1000-, and 10000-draw simulations.
## Simulation¶
One common way to understand the behavior of statistical techniques is to use simulation (often called Monte Carlo simulation). In a simulation, we use a psuedorandom number generator to make up data that follows particular patterns (or lack of patterns). We call this data synthetic data.
We then apply a statistical technique, such as correlation coefficient or a linear regression, to the synthetic data, and see how closely its results match the parameters we put in to our simulation. If the analysis reliably estimates the simulation’s parameters, we say it recovers the parameters. We can do this many times to estimate that reliability — we can run the simulation 1000 times, for example, and examine the distribution of the error of its parameter estimates to see if it is unbiased, and how broad the errors are.
This technique is commonly used in statistics research (that is, research about statistics itself, rather than research that uses statistics to study other topics) in order to examine the behavior of statistical methods. By simulating samples of different sizes from a population with known parameters, we can compare the results of analyzing those samples with the actual values the statistical method is supposed to estimate. Further, by mapping its behavior over a range of scenarios, we can gain insight into what a statistical technique is likely doing with the particular data we have in front of us.
This is distinct from bootstrapping. In bootstrapping, we are resampling our sample to try to estimate the sampling distribution of a statistic with respect to the population our sample was drawn from; we have actual data, but do not know the actual population parameters. In simulation, we know the population parameters, and do not have any actual data because we make it all up with the random number generator.
## Generating Random Numbers¶
NumPy’s Generator class is the starting point for generating random numbers. It has methods for generating numbers from a range of distributions. For more sophisticated distributions, the various distributions in the scipy.stats also support random draws.
Random number generators have a seed that is the starting point for picking numbers. Two identical generators with the same seed will produce the same sequence of values.
We can create a generator with np.random.default_rng:
rng = np.random.default_rng(20201014)
This will return a numpy.random.Generator, just like numpy.random.default_rng().
In my class examples, I have been using the current date as my seed. If you do not specify a seed, it will pick a fresh one every time you start the program; for reproducibility, it is advised to pick a seed for any particular analysis. It’s also useful to re-run the analysis with a different seed and double-check that none of the conclusions changed.
We can then use the random number generator to generate random numbers from various distributions. It’s important to note that random does not mean uniform — then uniform distribution is just one kind of random distribution.
For example, we can draw 100 samples from the standard normal distribution ($$\mu = 0$$, $$\sigma = 1$$) using standard_normal():
xs = rng.standard_normal(100)
## Warmup: Correlation (10%)¶
If two variables are independent, their correlation should be zero, right? We can simulate this by drawing two arrays of 100 standard normal variables each, and computing their correlation coefficient:
xs = pd.Series(rng.standard_normal(100))
ys = pd.Series(rng.standard_normal(100))
xs.corr(ys)
Code Meaning
This code takes 100 draws (or samples) from the standard normal, twice (once for xs and again for ys).
Mathematically, we write this using $$\sim$$ as the operator “drawn from”:
\begin{split}\begin{align*} x & \sim \mathrm{Normal}(0, 1) \\ y & \sim \mathrm{Normal}(0, 1) \\ \end{align*}\end{split}
✅ Run 1000 iterations of this simulation to compute 1000 correlation coefficients. What is the mean and variance of these simulated coefficients? Plot their distribution. Are the results what you expect for computing correlations of uncorrelated variables?
Tip
What you need to do for this is to run the code example above — that computes the correlation between two 100-item samples — one thousand times. This will draw a total of 200,000 numbers (100 each for x and y, in each simulation iteration).
✅ Repeat the previous simulation, but using 1000 draws per iteration instead of 100. How does this change the mean and variance of the resulting coefficients?
Tip
Now you need to modify the code to draw 1000 normals for x and 1000 normals for y in each iteration. Remember that the example above is drawing 100 normals for each variable.
Remember the covariance of two variables is defined as:
$\Cov(X, Y) = \E[(X - \E[X]) (Y - \E[Y])] = \frac{1}{n} \sum_{i} (x_i - \bar{x}) (y_i - \bar{y})$
And the correlation is:
$r = \frac{\Cov(X, Y)}{\sigma_X \sigma_Y} = \frac{\Cov(X, Y)}{\sqrt{\Cov(X, X)} \sqrt{\Cov(Y, Y)}}$
If we want to generate correlated variables, we can do so by combining two random variables to form a third:
\begin{split}\begin{align*} x & \sim \mathrm{Normal}(0, 1) \\ y & \sim \mathrm{Normal}(0, 1) \\ z & = x + y \end{align*}\end{split}
We can draw them with:
xs = pd.Series(rng.standard_normal(100))
ys = pd.Series(rng.standard_normal(100))
zs = xs + ys
With these variables, we have:
\begin{split}\begin{align*} \sigma_X & = 1 \\ \E[X] & = 0 \\ \sigma_{Y} & = 1 \\ \E[Y] & = 0 \\ \E[Z] & = \E[X + Y] = \E[X] + \E[Y] = 0 \end{align*}\end{split}
This last identity is from a property called linearity of expectation. We can now determine the covariance between $$X$$ and $$Z$$. As a preliminary, since $$X$$ and $$Y$$ are independent, their covariance $$\Cov(X, Y) = 0$$. Further, their independence implies that $$\E[X Y] = \E[X]\E[Y]$$, which from the equations above is $$0$$.
With that:
\begin{split}\begin{align*} \Cov(X, Z) & = \E[(X - \E[X])(Z - \E[Z])] \\ & = \E[X (X + Y)] & \text{since \E[X] = \E[Z] = 0} \\ & = \E[X^2 + XY] \\ & = \E[X^2] + \E[X Y] \\ & = \E[X^2] \\ & = \Var[X] & \text{since \E[X] = 0} \\ & = \sigma_X^2 = 1 \end{align*}\end{split}
The correlation coefficient depends on $$\Cov(X,Z) = 1$$, $$\Var(X) = 1$$, and $$\Var(Z)$$. We can derive $$\Var(Z))$$ as follows:
\begin{split}\begin{align*} \Var(Z) & = \E[(Z - \E[Z])^2] \\ & = \E[Z^2] & \text{since \E[Z] = 0} \\ & = \E[(X + Y)^2] \\ & = \E[X^2 + 2 X Y + Y^2] \\ & = \E[X^2] + 2 \E[X Y] + \E[Y^2] & \text{by linearity of expectation} \\ & = \Var(X) + \Var(Y) & \text{since both variables' means are 0} \\ & = \sigma_X^2 + \sigma_{Y}^2 = 2 \end{align*}\end{split}
Therefore we have $$\sigma_X = 1$$ (from its distribution), and $$\sigma_Z = \sqrt{2}$$, and so the correlation
$r_{XZ} = \frac{\Cov(X,Z)}{\sigma_X \sigma_Z} = \frac{1}{1 \cdot \sqrt{2}} = 0.707$
Covariance
You can compute the covariance with the pandas.Series.cov() method. It’s instructive to also plot that!
✅ Run 1000 iterations simulating these correlated variables to compute 1000 correlation coefficients (xs.corr(zs)), with 100 draws of each variable per iteration. Compute the mean and variance of these coefficients, and plot their distributions. Does this match what we expect from the analytic results? What happens when we compute correlations of 1000 draws in each iteration? What about 10000 draws?
## Linear Regression (35%)¶
If we want to simulate a single-variable linear regression:
$y = \alpha + \beta x + \epsilon$
there are four things we need to control:
• the distribution of $$x$$
• the intercept $$\alpha$$
• the slope $$\beta$$
• the variance of errors $$\sigma_\epsilon^2$$
Remember that the linear regression model assumes errors are i.i.d. normal, and the OLS model will result in a mean error of 0; thus we have $$\epsilon \sim \mathrm{Normal}(0, \sigma_\epsilon)$$. Sampling data for this model involves the following steps:
1. Sample $$x$$
2. Sample $$\epsilon$$
3. Compute $$y = \alpha + \beta x + \epsilon$$
Let’s start with a very simple example: $$x$$ is drawn from a standard normal, $$\alpha=0$$, $$\beta=1$$, and $$\sigma_\epsilon^2 = 1$$.
xs = rng.standard_normal(1000)
errs = rng.standard_normal(1000)
ys = 0 + 1 * xs + errs
data = pd.DataFrame({
'X': xs,
'Y': ys
})
✅ Fit a linear model to this data, predicting $$Y$$ with $$X$$. What are the intercept and slope? What is $$R^2$$? Are these values what you expect? Plot residuals vs. fitted and a Q-Q plot of residuals to check the model assumptions - do they hold?
✅ Repeat the simulation 1000 times, fitting a linear model each time. Show the mean, variance, and a distribution plot of the intercept, slope, and $$R^2$$ from these simulations.
Extracting Parameters
The RegressionResults class returned by OLS.fit() contains the model parameters. The .params field has the coefficients (including intercept), and .rsquared has the $$R^2$$ value:
fit.params['X']
✅ Fit a model to data with $$\alpha=1$$ and $$\beta=4$$. Are the resulting model parameters what you expect? How did $$R^2$$ change, and why? Do the linear model assumptions still hold? What are the distributions of the slope, intercept, and $$R^2$$ if you do this 1000 times?
## Nonlinear Data (15%)¶
✅ Generate 1000 data points with the following distributions and formula:
\begin{split}\begin{align*} x & \sim \mathrm{Normal}(0, 1) \\ \epsilon & \sim \mathrm{Normal}(0, 5) \\ y & = 10 + 5 e^x + \epsilon \end{align*}\end{split}
✅ Fit a linear model predicting $$y$$ with $$x$$. How well does the model fit? Do the assumptions seem to hold?
✅ Draw a scatter plot of $$x$$ and $$y$$.
Drawing Normals
You can draw from $$\mathrm{Normal}(0, 5)$$ either by using tbe normal() method of Generator, or by drawing an array of standard normals and multiplying it by 5. This is because the normal distribution is in the scale-location family of distributions.
Exponentiation
The NumPy function numpy.exp() computes $$e^x$$.
✅ Repeat with $$y = -2 + 3 x^3 + \epsilon$$
## Non-Normal Covariates (15%)¶
✅ Generate 1000 data points with the model:
\begin{split}\begin{align*} y & = 10 + 0.3x + \epsilon \\ \epsilon & \sim \mathrm{Normal}(0, 1) \\ x & \sim \mathrm{Gamma}(2, 1) \end{align*}\end{split}
• Plot the distributions of $$X$$ and $$Y$$
• Fit a linear model predicting $$y$$ with $$x$$
• How well does this model fit? How much of the variance does it explain? Do the assumptions seem to hold? Does the linear regression seem appropriate to the data?
Gamma Distributions
You can draw 1000 samples from the $$\mathrm{Gamma}(2, 1)$$ distribution with numpy.random.Generator.gamma():
rng.gamma(2, 1, 1000)
## Multiple Regression (10%)¶
Now we’re going to look at regression with two or more independent variables.
We will use the following data generating process:
\begin{split}\begin{align*} x_1 & \sim \mathrm{Normal}(10, 2) \\ x_2 & \sim \mathrm{Normal}(-2, 5) \\ \epsilon & \sim \mathrm{Normal}(0, 1) \\ y & = 1 + 0.5 x_1 + 3 x_2 + \epsilon \end{align*}\end{split}
Scale-Location Distribution
To draw from $$\mathrm{Normal}(\mu, \sigma)$$, you can draw xs from a standard normal and compute xs * σ + μ.
✅ Fit a linear model y ~ x1 + x2 on 1000 data points drawn from this model. What are the intercept and coefficients from the model? Are they what you expect? Check the model assumptions — do they hold?
Multivariate Normals
You can draw both $$x_1$$ and $$x_2$$ simultaneously with:
xs = rng.multivariate_normal([10, -2], [[2, 0], [0, 5]], 1000)
# turn into a data frame
xdf = pd.DataFrame(xs, columns=['X1', 'X2'])
The multivariate normal distribution is parameterized by a list (or array) of means, and a positive symmetric covariance matrix defined as follows:
$\begin{split}\begin{bmatrix} \Var(X_1) & \Cov(X_1, X_2) \\ \Cov(X_2, X_1) & \Var(X_2) \end{bmatrix}\end{split}$
That is, the diagonals of the matrix are the variances of the individual variables, and the other cells are the covariances between pairs of variables. The example code sets up the following matrix:
$\begin{split}\begin{bmatrix} 2 & 0 \\ 0 & 5 \end{bmatrix}\end{split}$
## Correlated Predictors (10%)¶
Now we’re going to see what happens when we have correlated predictor variables. Remember I said those were a problem?
We’re going to use the multivariate normal from the hint in the previous part to draw correlated variables $$X_1$$ and $$X_2$$ to use as predictors. We will use the following procedure:
1. Draw 1000 samples of variables $$X_1$$ and $$X_2$$ from a multivariate normal with means $$\langle 1, 3 \rangle$$, variances of 1, and a covariance $$\Cov(X_1, X_2) = 0.85$$:
xs = rng.multivariate_normal([1, 3], [[1, 0.85], [0.85, 1]], 1000)
2. Draw $$\epsilon \sim \mathrm{Normal}(0, 2)$$
3. Compute $$y = 3 + 2 x_1 + 3 x_2 + \epsilon$$
✅ Show a pairplot of our variables $$X_1$$, $$X_2$$, and $$Y$$. What do we see about their distributions and relationships?
✅ Fit a linear regression for y ~ x1 + x2. How well does it fit? Do its assumptions hold?
✅ Run this simulation (drawing 1000 variables and fitting a linear model) 100 times. Show the mean, variance, and appropriate distribution plots of the estimated intercepts and coefficients (for x1 and x2).
✅ Repeat the repeated simulation for a variety of different covariances from 0 to 1 (including at least 0, 0.9, 0.99, and 0.999). Create line plots (or a single line plot with multiple colors) that show how the variance of the estimated regression parameters (intercept and $$x_1$$ and $$x_2$$ coefficients) change as you increase the correlation (covariance) between $$X_1$$ and $$X_2$$.
Repeated Repeats
One iteration of the simulation is the following steps:
1. draw variables
2. compute result (linear model intercept & coefficients)
Repeating that is performing this simulation 100 times, so we can compute the variance of our linear model’s estimate.
To repeat the repeated simulation, you need to do that multiple times:
for real_cov in COV_LIST:
for rep in range(100):
# draw numbers
# fit parameters
Note
I didn’t ask you to include 1 in your selected covariances - what happens if you do? How does that plot differ from a plot that only goes up to 0.999 or 0.9999?
## Reflection (5%)¶
Write a couple of paragraphs about what you learned from this assignment.
## Expected Time¶
I’m providing here some estimates of how long I expect each part might take you.
1. Warmup: 1 hour
2. Linear Regression: 2.5 hours
3. Nonlinear Data: 1 hour
4. Non-normal Covariates: 1 hour
5. Multiple Regression: 1 hour
6. Correlated Predictors: 2 hours
7. Cleanup and Reflection: 1 hour
|
{}
|
# May 23, 2018 SRM 734: The Hacking CardCounter Problem
Single Round Marathon (SRM) 734 had a simplified card counting problem, CardCounter. Though solving the problem will not win the programmer Hollywood-level fame and fortune, the solution proves to be a good mental exercise and is a bit difficult to come by.
Blackjack is the daring card game where the winner scores as close to twenty-one points as possible. If a player does not “bust” or have a total higher than twenty-one and has a total higher than the dealer, the player wins. Card counting allows the player to take the element of luck out of the game by figuring out the chances that a particular card is played next in the sequence. For the following problem, two cards are dealt. One of the dealer’s cards will have a known value and the other will have an allocated value that is unknown to the problem solver.
The player can choose to take a “hit” and be dealt another card. He can keep going until he reaches a total number of points greater than or equal to twenty-one or decides to “stand” with the total held. The dealer will then reveal his card and take the hit if his total is below seventeen. Once he reaches, seventeen, he stands. If the player has a total higher than the dealer and has not gone over twenty-one, he wins. If the dealer has a total higher than the player or the player goes bust, he wins.
For this problem, the deck will have 10 elements, and each element will be valued between 0 and 4 inclusive. The deal will have a value between 1 and 10. The player will be an array with two elements where each element will be between 1 and 10 inclusive. The cards that remain in the deck will be no more than sixteen, and the total value of all the cards showing and remaining in the deck is at least fifty-six. The problem statement determines that the deck is passed as an array of integers, the dealer is passed as an integer, and the player’s cards are passed an array of integers. The probability of the player winning the hand is returned. Now that the rules have been stated, let us look at solving the problem.
The first thing to do to solve the problem is determine when the dealer and the player go bust. The dealer will go bust at a lower value than the player, and making sure that this is accounted for in the code is important. The preliminary pseudocode for the problem is as follows:
deck = argv[0]
dealer_probability, player_probability
for card in deck:
dealer_score = argv[1]
player_score = sum(argv[2])
dealer_score += card
player_score += card
if dealer_score > 17:
player_probability += 1
if player_score > 21:
dealer_probability += 1
else:
continue
return player_probability/(dealer_probability+player_probability)
This preliminary approach will not pass the test cases. For example, if the player or dealer decides to hold instead of incrementing their score, the program will not take this into account. The algorithm needs to be further fine-tuned. One way to do this is by checking how close the player and dealer are to their ideal score. For example, if the player has a score of twenty and the deck has cards that have a value of two or higher, the player should stand in order to increase the chances of the ]player winning. If the player has a score of nineteen and the deck has a 70% chance of returning a card that is two and a 0% chance that the dealer can advantageously increase the dealer’s point value with a hit, the player should take the hit.
In order to take account of this programmatically, one can add states to take into account how close a person is to winning, multiply it with the dealer’s chance of winning while in that state, and return the overall probability for all the states. The pseudocode that handles these states is written as such:
for card in deck:
if dealer_score + card <= 17:
dealer_score += card
else:
continue
for card in deck:
if player_score + card <= 21:
player_score += card
else:
continue
if dealer_score > player_score:
dealer_probability += 1
elif player_score > dealer_score:
player_probability += 1
else:
continue
return player_probability/(dealer_probability+player_probability)
This takes into account whether or not the person playing will stand or will continue to increment their score. All the possibilities for the cards are considered. Now that the pseudocode has been written, the reader can go ahead and tackle the problem. The solution will be handled in O(n²) time.
maxwells_daemon
Guest Blogger
categories & Tags
UNLEASH THE GIG ECONOMY. START A PROJECT OR TALK TO SALES
Close
|
{}
|
# Positioning SVG elements using CSS
Assume the following svg document:
<svg version="1.1" baseProfile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg">
<text x="20" y="20">My text</text>
</svg>
Now what i want to do is reposition this text using css.
I have tried adding style="dx:20" and style="transform: translate(20)". Both have no effect in firefox and safari. Adding these as normal attributes works fine but then i can't split the positioning from the actual code. Setting x, y, left and top in the style isn't working either.
Is there a way to position an svg element using css?
-
I think i'll use symbols as a decent alternative. The user needs to specify a bit more manually but at least i don't have to pass layout-stuff through my library code. – Yorick Sijsling Feb 4 '10 at 14:00
Did you find a solution to this problem Yorick? I was hoping to position my SVG with CSS document but the positioning is not working sadly... – Kayote Apr 4 '11 at 4:48
Nope, never found a solution. I think David Thomas' answer is the best you will find right now. – Yorick Sijsling Apr 19 '11 at 14:33
I've managed to move some SVG text in chrome using the following CSS:
text.identity{
transform: translate(74px,0px);
-ms-transform: translate(74px,0px); /* IE 9 */
-webkit-transform: translate(74px,0px); /* Safari and Chrome */
-o-transform: translate(74px,0px); /* Opera */
-moz-transform: translate(74px,0px); /* Firefox */
}
However, it's not budging in Firefox...
-
I think this is one of the most expense ways I have ever seen to move text – David Diez Jan 25 '13 at 19:52
You're right, but sadly SVG and CSS are wedded as well as we'd like right now. If you have a faster way I'd love to see it. – pluke Jan 28 '13 at 9:15
Slight grammar correction *are = aren't – pluke Jan 28 '13 at 10:14
As of Firefox 23, -moz-transform is not required; -transform works fine! – HRJ Aug 31 '13 at 6:38
Here is a hacky possibility to position specifically text-elements purely by CSS, by abusing the attributes ‘letter-spacing’ for the x-coordinate and ‘baseline-shift’ for the y-coordinate:
<defs>
<font><font-face font-family="cssPosAnchor" />
</font>
<style type="text/css"><![CDATA[
#cssPos {
font-family:cssPosAnchor;
letter-spacing:10px; /* x-coordinate */
}
#cssPos>tspan {
font-family:serif;
letter-spacing:normal;
baseline-shift:-30px; /* negative y-coordinate */
}
]]>
</style>
</defs>
<text id="cssPos">.<tspan>CSS-Positioned Text!</tspan></text>
‘baseline-shift’ is only applicable on ‘tspan’ Elements, thus making the inner <tspan> necessary in the presented code. Positive values for baseline-shift move the text upwards, opposite of the normal direction in the svg.
‘letter-spacing’ needs an initial letter to have an effect, thus making the . necessary. To eliminate the width of this first letter, we use the special made font cssPosAnchor, where the dot has no width and no shape. The following <tspan> additionally restores font and letter-spacing.
## Scope
Should work in every conforming SVG implementation.
There is one indefinite limitation though for negative x-coordinates. The specification for the ‘letter-spacing’ attribute says: “Values may be negative, but there may be implementation-specific limits.”
## Compatibility
Text ‘direction’ change should work just fine, when imposed on the inner <tspan>.
A non-standard ‘writing-mode’ must be imposed on the outer <text>. There will most certainly be problems with that.
The probably more important ‘text-anchor’ values middle and end can be made possible like this:
<defs>
<font><font-face font-family="cssPosAnchor" />
</font>
<style type="text/css"><![CDATA[
#cssPos {
font-family:cssPosAnchor;
letter-spacing:100px; /* x-coordinate */
word-spacing:-200px; /* negative double x-coordinate */
}
#cssPos>tspan {
font-family:serif;
word-spacing:normal;
letter-spacing:normal;
baseline-shift:-30px; /* negative y-coordinate */
}
#cssPos {
text-anchor=middle;
}
]]>
</style>
</defs>
<text id="cssPos">.<tspan>CSS-Positioned Text!</tspan> .</text>
The ‹space›. before the closing <\text> tag produces spacing equal to minus x-coordinate. So the inner <tspan> is moved around but preserves it's space in the <text> as if it was still there.
Since there may be implementation-specific limits on negative values for the spacing attributes, this is not guaranteed to work on all clients!
-
At the moment, it seems -according to Shelley Powers, in her A List Apart Article "Using SVG for Flexible, Scalable and Fun Backgrounds: Part I" and "Part II"- that CSS is not currently best-suited to positioning of SVG. In fact it seems to be quite a minefield to incorporate SVG into a web-page, without directly embedding it within the html itself.
I hope that there are solutions to be found, and, indeed, Powers does offer a couple of workarounds, to enable proper separation of style and content for SVG. I'd hazard a guess that the current problems are the relative new-ness of the concept/standard (relative to, for example, .gif or even .png...), sadly.
I'm sorry I can't offer a better answer. =/
-
I warn you i'm a relative beginner but what about "x" and "y" and assigning these with number and "px"
maybe:
left: 290px; top: 1200px;
or
x:30px; y:50px;
and
text-anchor:start;
Sample:
<text
xml:space="preserve"
style="font-size:32;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-align:start;line-height:125%;writing-mode:lr-tb;text-anchor:start;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Comic Sans MS;-inkscape-font-specification:Comic Sans MS Bold"
x="131.42857"
y="269.50504"
id="text2383"
sodipodi:linespacing="125%"><tspan
sodipodi:role="line"
id="tspan2385"
x="131.42857"
y="269.50504">Position ze text</tspan></text>
-
Thanks, never thought about using left and top. But these aren't working either. I have updated my question to include these. – Yorick Sijsling Feb 4 '10 at 9:12
I don't think this is right at all. – mtpain Jan 27 at 19:24
I came here looking for a fix but fixed the issue myself, thought I would share:
transform: translate(100px, 100px)
Appears to work in all modern browsers except for Internet Explorer, right up until Microsoft Edge (which isn't even out yet) which is quite disappointing. The elements I've tested on are:
<path>
<polygon>
<g>
The only issue I've had is with <text> elements, and the solution there is to wrap the <text> in a <g> and apply the transformation to that. That should also work for any elements I haven't yet tested that have issues with transform: translate().
I haven't found a decent fallback for Internet Explorer, instead I've made sure that the transforms aren't vital to the function of the SVG.
-
|
{}
|
alma2011
# ALMA in the Coming Decade - A Development Workshop.
## ALMA in the Coming Decade: A Development Workshop March 21-22, 2011, NRAO, Charlottesville, Virginia
Image courtesy Tania Burchell (NRAO)
### ALMA in the Coming Decade: A Development Workshop
ALMA will transform astronomy beginning with Early Science results later this year. It will reach full operation by 2013 and will eclipse any current millimeter or submillimeter array in sensitivity and resolution by nearly two orders of magnitude. ALMA will operate from 3mm to 0.3mm across a decade of nearly complete frequency access as enabled by its broad bandwidth receivers, powerful correlators and spectacular site. Having invested ~$1.3B to realize the biggest historical advance in ground-based astronomy, it is vital to maintain and expand its capabilities. Toward this end, the ALMA Operations Plan envisages an ongoing program of development and upgrades which may include hardware, software or data analysis tools. With a modest investment of less than 1% of capital cost per year (eventually about$13 million) divided among the three funding regions (North America, Europe, East Asia), ALMA will continue to lead astronomical research through the 2011-2020 decade and beyond.
In recent years, several programs which could spearhead a development plan have been identified by the scientific community. For example, ALMA's wavelength coverage could be extended to cover from 1 cm to 200 microns and thereby encompass additional unique spectral features and important scientific topics. To further explore such ideas, the North American ALMA Science Center (NAASC) will soon invite Proposals from North American entities for studies relevant to the crafting of an ALMA Development Plan. All interested parties located within the North American ALMA partnership are eligible to participate in these studies.
The primary aims of these studies are:
• to give groups in North America the opportunity to propose ALMA upgrades that may later be implemented as part of the ALMA Development Plan;
• to support the development of conceptual and detailed designs for ALMA upgrades; and
• to encourage relevant long-term research and development in areas important for ALMA.
The completed studies will be used, together with similar studies from the other ALMA partners, to devise and implement the ALMA Development Plan. To help initiate this process, we invite you to attend an ALMA Development Workshop in Charlottesville on 21-22 March 2011. At the workshop we will present the scientific motivation for a suite of key science goals driving possible development projects in hopes of stimulating further discussion and thinking. The second part of the workshop will allow us to explore ideas for development projects in more detail and how these projects can be effectively managed. An agenda will be forthcoming. While we now plan no formal program for the second day, participants are invited to present their ideas for participation in ALMA/NA Development in a discussion session.
|
{}
|
Files in this item
FilesDescriptionFormat
application/pdf
9010841.pdf (8MB)
(no description provided)PDF
Description
Title: A parallel algorithm for sparse unsymmetric LU factorization Author(s): Davis, Timothy Alden Doctoral Committee Chair(s): Yew, Pen-Chung Department / Program: Electrical and Computer Engineering Discipline: Electrical Engineering Degree Granting Institution: University of Illinois at Urbana-Champaign Degree: Ph.D. Genre: Dissertation Subject(s): Mathematics Engineering, Electronics and Electrical Computer Science Abstract: This thesis presents a parallel algorithm for the direct LU factorization of general unsymmetric sparse matrices. The algorithm, D2, is based on a new nondeterministic parallel pivot search that finds a compatible pivot set S of size m, followed by a parallel rank-m update. These two steps alternate until switching to dense matrix code or until the matrix is factored. The algorithm is based on a shared-memory MIMD model and takes advantage of both concurrency and (gather-scatter) vectorization. Experimental comparisons on an Alliant FX/8 show that the method results in shorter elimination trees for matrices with highly asymmetrical nonzero structure than those for previous methods that work with the symmetric structure of A + ${\bf A\sp{T}}$ or ${\bf A\sp{T}A}$ (such as George and Ng's Sparspak-C or Duff and Reid's multifrontal method). The algorithm exploits more parallelism in the pivot search phase than previous algorithms which do not force a symmetric structure onto the matrix during any phase of the factorization. Additional experimental comparisons include fillin, amount of work, numerical stability, memory usage, and run time. The nondeterministic behavior of the D2 algorithm and other performance metrics are analyzed on an Alliant FX/8, a Cray-2, and a Cray-XMP/48. Enhancements to PSolve, a pairwise pivoting algorithm, are discussed, and a software tool for developing sparse matrix algorithms and observing their dynamic behavior on a Sun workstation is presented. The tool was instrumental in the development of the D2 algorithm. Possible extensions to the D2 algorithm are discussed, including the use of dense matrix kernels and replacing the synchronization structure in the pivot search with a software combining tree. Issue Date: 1989 Type: Text Language: English URI: http://hdl.handle.net/2142/20745 Rights Information: Copyright 1989 Davis, Timothy Alden Date Available in IDEALS: 2011-05-07 Identifier in Online Catalog: AAI9010841 OCLC Identifier: (UMI)AAI9010841
|
{}
|
# Angles on CP-violation in Higgs boson interactions
29 Mar 2019 · Bernlochner Florian U., Englert Christoph, Hays Chris, Lohwasser Kristin, Mildner Hannes, Pilkington Andrew, Price Darren D., Spannowsky Michael ·
CP-violation in the Higgs sector remains a possible source of the baryon asymmetry of the universe. Recent differential measurements of signed angular distributions in Higgs boson production provide a general experimental probe of the CP structure of Higgs boson interactions... We interpret these measurements using the Standard Model Effective Field Theory and show that they do not distinguish the various CP-violating operators that couple the Higgs and gauge fields. However, the constraints can be sharpened by measuring additional CP-sensitive observables and exploiting phase-space-dependent effects. Using these observables, we demonstrate that perturbatively meaningful constraints on CP-violating operators can be obtained at the LHC with luminosities of ${\cal{O}}$(100/fb). Our results provide a roadmap to a global Higgs boson coupling analysis that includes CP-violating effects. read more
PDF Abstract
## Code Add Remove Mark official
No code implementations yet. Submit your code now
## Categories
High Energy Physics - Phenomenology High Energy Physics - Experiment
|
{}
|
A. Three seamarks
time limit per test
2.0 s
memory limit per test
256 MB
input
standard input
output
standard output
The "Victory" ship sailed away from the shore to participate in an international regatta. Having no positioning device onboard the ship went off the course and got lost in the seas. Luckily, the captain could see three seamarks through his binoculars with their coordinates known. As everyone knows, binoculars make it is possible not only to observe the objects, but also measure their angular sizes, i.e angles between straight lines connecting objects' corner points with an observing eye. For example, if two seamarks are located at points M1 and M2, and the ship is at point K, then the angular size of segment M1M2 is an angle M1KM2.
You need to find the ship's coordinates by given angular sizes of two segments connecting seamarks M1 and M2, M2 and M3.
Input
The first line contains an integer n — number of possible locations of the seamarks (1 ≤ n ≤ 50 000). Each of the next n lines contains eight integers. The first six integers describe Cartesian coordinates of different points M1, M2, M3 that do not exceed 10 000 by absolute value; the next two integers from the range [1; 179] are angular sizes (in degrees) of segments M1M2 and M2M3. It is guaranteed that the solution exists for each of the test cases.
Output
For each location of the seamarks output coordinates of any possible ship position separated by space in a separate line. The answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
10 0 2 0 2 2 90 90
Output
1.0000000000 1.0000000000
|
{}
|
pyABC version: 0.9.2
Source code: https://github.com/icb-dcm/pyabc
## Authors¶
The package was mainly developed by Emmanuel Klinger. Dennis Rickert contributed through discussions and code. Lukas Sandmeir and Elba Raimundez contributed to the examples. Yannik Schälte contributed several new features.
## Contact¶
Copyright 2017 the pyABC developers
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
{}
|
# Centrifugal Force
Do your students ever confuse centripetal force and centrifugal force? Here is a video that addresses exactly that concept. The video uses a tether ball as a demonstration of the various forces at play.
|
{}
|
Show Summary Details
More options …
# Open Chemistry
### formerly Central European Journal of Chemistry
IMPACT FACTOR 2018: 1.512
5-year IMPACT FACTOR: 1.599
CiteScore 2018: 1.58
SCImago Journal Rank (SJR) 2018: 0.345
Source Normalized Impact per Paper (SNIP) 2018: 0.684
ICV 2017: 165.27
Open Access
Online
ISSN
2391-5420
See all formats and pricing
More options …
Volume 16, Issue 1
# Analysis of Metabolites in Cabernet Sauvignon and Shiraz Dry Red Wines from Shanxi by 1H NMR Spectroscopy Combined with Pattern Recognition Analysis
Jiangyu Zhu
• School of Food Science and Engineering, Yangzhou University, Yangzhou city, Jiangsu Province 225127, China
• Other articles by this author:
/ Boran Hu
• Corresponding author
• School of Food Science and Engineering, Yangzhou University, Yangzhou city, Jiangsu Province 225127, China
• Email
• Other articles by this author:
/ Jie Lu
• School of Food Science and Engineering, Yangzhou University, Yangzhou city, Jiangsu Province 225127, China
• Other articles by this author:
/ Shaochen Xu
• School of Food Science and Engineering, Yangzhou University, Yangzhou city, Jiangsu Province 225127, China
• Other articles by this author:
Published Online: 2018-06-01 | DOI: https://doi.org/10.1515/chem-2018-0052
## Abstract
Metabolomics technology based on proton nuclear magnetic resonance (1H NMR) spectroscopy combined with pattern recognition analysis was used to characterize the Cabernet Sauvignon and Shiraz dry red wines vinified in the Linfen of Shanxi Province, China, in 2016. The results showed that there was a very significant difference between the metabolites of Cabernet Sauvignon and Shiraz dry red wines from the area of Linfen. Compared with Shiraz dry red wines, Cabernet Sauvignon dry red wines contained higher levels of proline, valine, tartaric acid, citric acid, malic acid, gallic acid, β-glucose and ethyl acetate, whereas 2,3-butanediol, lactic acid, choline, glycerol, α-D-glucuronic acid, succinic acid and alanine were present in lower levels. Application of NMR spectroscopy combined with pattern recognition analysis showed the discriminative power between wine varietals from the same production area. The loading plot from partial least squares discriminant analysis (PLs-DA) indicated that the key biomarkers for this differentiation were proline, tartaric acid, glycerol, lactic acid, choline, succinic acid and gallic acid, which was consistent with the result of quantitative analysis.
## 1 Introduction
Wine is one of the most popular beverages throughout the world. In recent years, with the globalization of viticulture and wine trade, vineyard growth has gradually increased in emergent viticultural countries. According to the data of 2013 form the International Organization of the Vine and Wine (OIV), wine production in China reached a high level to 2.1 Mhl [1]. Tremendous wealth is generated in wine sector, and the requirements of consumers to wine quality, security, and style diversification has also been more and more strict at the same time. How to improve the wine quality and enrich the diversification of the wine market has become an emergency issue [2]. The quality of the wines is determined by grape varieties, grape growing conditions, vintage, and the wine-making techniques. However, wine fraud such as adulteration and lack of authentication is constantly interfering the wine market. Hence, a robust analytical method in the verification of the wine authenticity and adulteration is necessary.
Recently the most popular and advanced method is metabolomics technology based on nuclear magnetic resonance spectroscopy. This method has great advantages of information analysis and structure determination, which can assess the entire process of fruit growing and wine making from a more direct perspective [3, 4]. In previous reports, Son et al. confirmed the applicability of metabolomics based on NMR and multivariate statistical data sets in determining the grape varietals and production areas [5]. López et al. used nuclear magnetic resonance (NMR) technique to analyze the metabolites of wine samples from nine wineries in the same producing area [6]. It was found that NMR technology could accurately distinguish the wines from different wineries which were geographically very close, and isopentanol and isobutanol compounds were the key biomarkers for this discrimination. Godelmann et al. investigated a total of about 600 samples of wines produced in Germany and the results indicated that the grape variety, the geographical origin, and the year of vintage of wines could be predicated 89% correctly on average by 1H NMR spectroscopy combined with multivariate statistical analysis [7]. Licia et al. also identified the authenticity of the typical Italian Denominazione di origine controllata (DOC) wines by the same method [8]. At present, metabolomics technology based on nuclear magnetic resonance spectroscopy (1H NMR) has entered a new stage and each NMR spectrum and could be regarded as the individual “fingerprint” of a wine sample, containing the information of variety, origin, vintage, physiological state, technological treatment, fermentation and other environmental factors, such as climate, soil composition and humidity, light and rainfall [9, 10, 11, 12].
In emergent viticultural countries, the annual consumption of wine is very high, and most of their qualities are quite uneven, and wine fraud is also commonly seen in recent years. The widespread market of the corresponding wines deserves deeper studies on the traceability and authenticity of the wines [13]. The application of NMR-based metabolomics with multivariate statistical data sets in verification of the wine authenticity and adulteration should be expanded. In addition, it is necessary to establish “Fingerprints” library of wine in the main production areas in China. As two of the most popular and widely grown grapes in China, Cabernet Sauvignon and Shiraz from Linfen of Shanxi province was chosen in this research. Their characteristic metabolites were analyzed by NMR technique, and the biomarkers for the differentiation were identified by the pattern recognition analysis. This research provides a benchmark for further comparative study on the wine quality and the verification of the wine authenticity.
## 2.1 Sampling
Cabernet Sauvignon and Shiraz grapes were grown in the Linfen area of Shanxi Province. The climate was warm and the accumulated temperature above 10°C was 4101 to 4600°C·d. Heat in this producing area was sufficient and the annual rainfall is 550-600mm, with the hydrothermal coefficient less than 1.5. The frost-free period was 180-220 days and the temperature difference between day and night was 12-20°C, which was suitable for grapes to grow and accumulate sugar. The mean content of soil available phosphorus, potassium and alkali-hydrolyzed nitrogen at 0-20 cm soil depths were 14.15, 141.80 and 63.29 mg/kg, respectively.
Single varieties of wines were all brewed in 2016 by a standard process using the following techniques: De-stemmed and crushed the fruits, and then added the yeast to ferment at 25°C for 8-10 days, followed by pressing the pomace gently. The wine was separated and tank-switched, and then it was sampled for pretreatment. Physical and chemical indicators of the wine samples were all in line with the standards of the International Organisation of Vine and Wine [14]. All samples were stored at -4°C.
## 2.2 Reagents and Apparatus
Oxalic acid, sodium oxalate (Shanghai Suyi Chemical Reagent Co., Ltd., China), heavy water (D2O, deuterium content > 99.9%; Qingdao Tenglong Microwave Technology Co., Ltd., China), 4,4-dimethyl-4-silapentane-1-sulfonic acid (DSS).
Nuclear Magnetic Resonance Spectrometer (AVANCE600, Bruker Co., Ltd., German); Ultra-low Temperature Freezer (ULT178-6-V49, Revco Co., Ltd., USA); Vacuum Freeze Dryer (SNL315SV-230, Thermo Co., Ltd., USA); Micro Vortex Mixer (WH-3, Shanghai Huxi Analytical Instrument Co., Ltd., China); Desktop High-speed Centrifuge (TG16A-WS, Luxiangyi Centrifuge Instrument Co., Ltd., China);
## 2.3.1 Sample Pretreatment
10 mL of wine samples were taken and then centrifuged at the speed of 3000 rpm for 20 min at -4°C. After the centrifugation, 3 mL of the supernatant was transferred and pre-frozen at -80°C overnight. After 48 h of freezedrying, 400 μL of oxalate buffer (pH 4), 140 μL of D2O and 60 μL of 0.5% DSS were added, and the mixture was centrifuged at 13,000 rpm for 20 min. At last, 500 μL of the supernatant was loaded into a 5 mm nuclear tube for NMR analysis. Each sample was tested 8 times.
## 2.3.2 NMR Data Collection
The 1H NMR spectra of the wine samples were collected from the AVANCE 600 nuclear magnetic resonance spectrometer. NMR analysis was carried out at a constant temperature of 298 K, and an H, C-sensitive cryogenic probe was used. The proton frequency and spectral width was 600.23 MHz and 7183.9 Hz, respectively. The number of sampling points was 32 K. The relaxation delay was set to 2 s and the sampling time was set to 2.3 s. For the mixing time, 100 ms was chosen. The linewidth enhancement factor was 0.3 Hz. The Noesygpprld sequence was used to suppress the water peak signal, and the number of scans was set at 256 times.
## 2.4 Multivariate Statistical Analysis
1. The chemical shift interval between 0-10.0 ppm in the nuclear magnetic resonance spectrum was integrated at the section of 0.005 ppm using Software AMIX. The residual ethanol peaks of 1.18-1.22 ppm and 3.57-3.72 ppm, residual DSS peaks of -0.5-0.5 ppm, 1.74-1.84 ppm and 2.90-2.95 ppm, and residual water peaks of 4.8-4.96 ppm were all removed.
2. The data were normalized and then introduced into Software SIMCA-P12.0 for pattern recognition analysis. Principal components analysis (PCA) was performed to visualize the acquired data, reduce the dimension of the high-dimensional data, remove the signal noise, and observe the discrete trend between samples.
3. To create a more reasonable regression model, partial least squares discriminant analysis (PLS-DA) was performed to sharpen the separation between observations groups. A maximum separation among classes could be obtained by rotating PCA components. In addition, PLS-DA is also helpful to understand which component carries the class separating information.
4. An external model validation experiment was carried to verify the degree of fitting of PLS-DA.
Metabolite content was obtained by calculating the ratio of the peak area of the protons on a given group of the substance to be measured, to that of the internal standard DSS in the one-dimensional 1H-NMR spectrum [15]. The mass concentration u (g /L) of metabolites was calculated as follows:
$u=msv=(AS/nS)×MS(AR/nR)×MR×mRV$
Note: AS is the integral area of the selected signal for the tested sample; AR is the integral area of the selected signal for the internal standard DSS; ns is the number of protons contained in the tested sample by the integral signal; nR is the number of protons contained in the internal standard DSS by the integral signal; MS is the relative molecular mass of the tested sample; MR is the relative molecular mass of the internal standard DSS; mR is the mass of the internal standard DSS.
Ethical approval: The conducted research is not related to either human or animals use.
## 3.1 Pattern Recognition of Cabernet Sauvignon and Shiraz Dry Red Wine from the Same Producing Area
As illustrated from the 1H NMR spectrum of Cabernet Sauvignon and Shiraz (Figure 1), the sensitivity of the proposed method was good and the signal of the major metabolites of Cabernet Sauvignon and Shiraz red wine could be well separated and recognized. Combining relevant literature [16, 17, 18, 19] and the NMR spectra obtained in this experiment, the associated chemical shift of the main metabolites was present in Table 1.
Figure 1
1H NMR spectrum of Cabernet Sauvignon and Shiraz dry red wines.
Table 1
1H NMR assignment of metabolites in Cabernet Sauvignon and Shiraz dry red wines.
The number of peaks a signal has was classified: s (singlet), d (doublet), t (triplet), q (quartet), m (multiplet) and dd (doublet of doubles).
At present, NMR fingerprinting technique combined with pattern recognition analysis has been widely used in many fields [20, 21, 22]. NMR data of the dry red wine samples were imported into SIMCA P-12.0 software for principal component analysis. PCA scores plot derived from the 1H NMR spectra of Cabernet Sauvignon and Shiraz dry red wines was illustrated in Figure 2. As seen from the score plot, there was an obvious distinction between Cabernet Sauvignon and Shiraz dry red wine, revealing the significant difference of the metabolites from these two wines. The cumulative contribution rate, R2X = 0.99, and Q2 = 0.967, indicating that the established PCA model was of good quality.
Figure 2
PCA scores plot based on the 1H NMR spectra of Cabernet Sauvignon and Shiraz dry red wines. Black solid circles and black solid triangles represent Cabernet Sauvignon and Shiraz dry red wines samples, respectively.
After the orthogonality correction, the PLS-DA model was established and the PLS-DA scores plot was shown in Figure 3. The cumulative contribution rate R2X = 0.592, R2Y = 0.754 and Q2 = 0.711. All three values were greater than 0.5, indicating that the model is valid. As seen from the PLS-DA scores plot, the distinction between Cabernet Sauvignon and Shiraz dry red wines was more obvious than that in PCA scores plot.
Figure 3
PLS-DA scores plot based on the 1H NMR spectra of Cabernet Sauvignon and Shiraz dry red wines. Black solid circles and black solid triangles represent Cabernet Sauvignon and Shiraz dry red wines samples, respectively.
A permutation test was used to verify the fitting degree of PLS-DA model, mainly evaluated by the slope of the regression line and the intercept of the regression line with the vertical axis. When the slope of the regression line was greater and the intercept was smaller, it indicated that there were more data to interpret the model and the predictive ability of the model was better [23]. Besides, it could also be evaluated by comparing the difference between R2 and Q2. The smaller the difference between the two values was, the smaller the difference between the data explained by the model and the predicted data was, indicating that the predictive ability of the model was excellent [24]. As seen from the validation plots of the permutation test in PLS-DA model (Figure 4), the values of R2 and Q2 did not exceed the quality parameter of the actual model in any arrangement, once again demonstrating that the model was reliable and predictive.
Figure 4
Validation plots based on the 1H NMR spectra of Cabernet Sauvignon and Shiraz dry red wines. Green triangles and blue squares represent R2 and Q2, respectively.
## 3.2 Metabolites analysis in Cabernet Sauvignon and Shiraz red wines
Major metabolites that made difference could be obtained from the PLD-DA loading plot. In the modeling process, values unrelated to the classification would be filtered out by orthogonal signal correction (OSC) [25].
PLS-DA loading plot of Cabernet Sauvignon and Shiraz dry red wines vinified at Shanxi in 2016 was shown in Figure 5. The higher peak in the loading plot indicated that content of the corresponding metabolite was higher in dry red wine, and the lower one indicated that content of the corresponding metabolite was lower. As seen from the loading plot, compared with Shiraz red wine vinified in Shanxi, Cabernet Sauvignon contained higher levels of proline, valine, tartaric acid, citric acid, malic acid, gallic acid, β-glucose and ethyl acetate, while content of 2,3-butanediol, lactic acid, choline, glycerin, α-D-glucuronic acid, succinic acid and alanine was lower. In Shiraz dry red wine, content of 2, 3-butanediol, choline, glycerol, succinic acid, lactic acid, alanine content was relatively higher whereas proline, tartaric acid and gallic acid was in lower levels. The main contributors to the differences were proline, tartaric acid, glycerin, lactic acid, choline, succinic acid and gallic acid.
Figure 5
PLS-DA loading plot based on the 1H NMR spectra of Cabernet Sauvignon and Shiraz dry red wines.
The main metabolites of Cabernet Sauvignon and Shiraz were quantitatively analyzed and the result was as shown in Figure 6. Significant difference between the main metabolites content was observed, consistent with the result obtained from PLS-DA loading plot.
Figure 6
Content of the main metabolites in Cabernet Sauvignon and Shiraz dry red wines. Asterisks indicate the significant difference (p < 0.05)between the metabolite content of Cabernet Sauvignon and Shiraz dry red wine.
Proline was the main amino acid in wines [26], and it was also the amino acid with the largest difference in content between the two samples. Proline has both, sweetness and bitterness, and is a complex amino acid. The content of proline had a direct impact on the depth and complexity of wine taste and flavor. Since proline in wines was not consumed by fermentation and maturation, the difference in the content of proline here is mainly attributed to the different wine varietals. For tartaric acid, it is a non-volatile acid, which could impart a dark red color to the wine. Its degree of enrichment in wines often depends on the grape varieties and the soil of the vineyard. For malic acid and lactic acid, the content of both does not simply depend on the type of grape. Unlike tartaric acid, in the process of grape maturation, malic acid is consumed by respiration, resulting in the decrease in acidity. In addition, malic acid will be further converted to softer lactic acid during the lactic fermentation of wine brewing [27]. According to the PLS-DA loading plot, we know that the content of citric acid in Cabernet Sauvignon is significantly higher than that in Shiraz, but the content of lactic acid is lower. It may be attributed to the difference in grape varieties, or the degree of fermentation.
Compared to Cabernet Sauvignon, Shiraz dry red wine contained a higher level of succinic acid and glycerol. Succinic acid is a by-product of yeast nitrogen metabolism during wine fermentation which has a mild fruity flavor, while glycerin is non-volatile and unscented, it does not influence the aroma of wine, but its sweetness and stickiness will also lead to the difference of sweetness and wine body thickness between Cabernet Sauvignon and Shiraz dry red wines.
## 4 Conclusion
In this study samples of Cabernet Sauvignon and Shiraz red wines vinified at Shanxi in 2016 were analyzed by 1H NMR, and the results showed that there was a notable difference between the metabolites of Cabernet Sauvignon and Shiraz. NMR technique combined with pattern recognition could excellently distinguish the two wines from each other, and the model established in this experiment was reliable, accurate and predictive.
The results provide a benchmark for further comparative study on the wine quality and the verification of the wine authenticity. The key contributors to the difference identified in this study may also be used to establish a quality evaluation system specifically for Cabernet Sauvignon and Shiraz dry red wines in China.
## Acknowledgements
The present work is supported by the National Natural Science Foundation of China (Project No.31271857).
## 5 References
• [1]
Alañón M.E., Pérez-Coello M.S., Marina M.L., Wine science in the metabolomics era, TrAC-Trend Anal. Chem., 2015, 74, 1-20.
• [2]
Famularo B., Bruwer J., Li E., Region of origin as choice factor: wine knowledge and wine tourism involvement influence, Int. J. Wine Bus. Res., 2010, 22, 362-385.
• [3]
López-Rituerto E., Savorani F., Avenoza A., et al., Investigations of La Rioja terroir for wine production using 1H NMR metabolomics, J. Agric. Food Chem., 2012, 60, 3452-3461.
• [4]
Young-Shick H., NMR-based metabolomics in wine science, Magn. Reson. Chem., 2011, 49, 13-21.
• [5]
Son H.S., Kim K.M., Van Den Berg F., et al., 1H nuclear magnetic resonance-based metabolomic characterization of wines by grape varieties and production areas, J. Agric. Food Chem., 2008, 56, 8007-8016.
• [6]
López-Rituerto E., Savorani F., Avenoza A., et al., Investigations of La Rioja terroir for wine production using 1H NMR metabolomics, J. Agric. Food Chem., 2012, 60, 3452-3461.
• [7]
Godelmann R., Fang F., Humpfer E., et al., Targeted and nontargeted wine analysis by 1H NMR spectroscopy combined with multivariate statistical analysis. Differentiation of important parameters: grape variety, geographical origin, year of vintage, J. Agric. Food Chem., 2013, 61, 5610-5619.
• [8]
Caruso M., Galgano F., Castiglione Morelli M.A., et al., Chemical profile of white wines produced from “Greco bianco” grape variety in different Italian areas by nuclear magnetic resonance (NMR) and conventional physicochemical analyses. J. Agric. Food Chem., 2011, 60, 7-15.
• [9]
Son H.S., Hwang G.S., Kim K.M., et al., 1H NMR-based metabolomic approach for understanding the fermentation behaviors of wine yeast strains, Anal. Chem., 2008, 81, 1137-1145.
• [10]
Son H.S., Hwang G.S., Kim K.M., et al., Metabolomic studies on geographical grapes and their wines using 1H NMR analysis coupled with multivariate statistics, J. Agric. Food Chem., 2009, 57, 1481-1490.
• [11]
Cassino C., Tsolakis C., Bonello F., et al. Effects of area, year and climatic factors on Barbera wine characteristics studied by the combination of 1H-NMR metabolomics and chemometrics, J. Wine Res., 2017, 28, 259-277.
• [12]
Du Y.Y., Bai G.Y., Zhang X., et al. Classification of wines based on combination of 1H NMR spectroscopy and principal component analysis, Chin. J. Chem., 2007, 25, 930-936.
• [13]
Viggiani L., Morelli M.A.C., Characterization of wines by nuclear magnetic resonance: a work study on wines from the Basilicata region in Italy, J. Agric. Food Chem., 2008, 56, 8273-8279.
• [14]
Oiv O., Compendium of International methods of wine and must analysis, International Organisation of Vine and Wine: Paris, France, 2009, 154-196. Google Scholar
• [15]
Hu B., Yue Y., Zhu Y., et al., Proton nuclear magnetic resonance-spectroscopic discrimination of wines reflects Genetic homology of several different grape (V. vinifera L.) cultivars, PloS one, 2015, 10, e0142840.
• [16]
Brescia M A., Caldarola V., De Giglio A., et al., Characterization of the geographical origin of Italian red wines based on traditional and nuclear magnetic resonance spectrometric determinations, Anal. Chim. Acta, 2002, 458, 177-186.
• [17]
Anastasiadi M., Zira A., Magiatis P., et al., 1H NMR-based metabonomics for the classification of Greek wines according to variety, region, and vintage. Comparison with HPLC data, J. Agric. Food Chem., 2009, 57, 11067-11074.
• [18]
Košir I.J., Kidric J., Identification of amino acids in wines by one-and two-dimensional nuclear magnetic resonance spectroscopy, J. Agric. Food Chem.,2001, 49, 50-56.
• [19]
Košir I.J., Kidrič J., Use of modern nuclear magnetic resonance spectroscopy in wine analysis: determination of minor compounds, Anal. Chim. Acta, 2002, 458, 77-84.
• [20]
Fotakis C., Kokkotou K., Zoumpoulakis P., et al., NMR metabolite fingerprinting in grape derived products: An overview, Food Res. Int., 2013, 54, 1184-1194.
• [21]
Ward J.L., Harris C., Lewis J, et al., Assessment of 1H NMR spectroscopy and multivariate analysis as a technique for metabolite fingerprinting of Arabidopsis thaliana, Phytochemistry, 2003, 62, 949-957.
• [22]
Krishnan P., Kruger N.J., Ratcliffe R G., Metabolite fingerprinting and profiling in plants using NMR, J. Exp. Bot., 2004, 56, 255-265.
• [23]
Szymańska E., Saccenti E., Smilde A.K., et al., Double-check: validation of diagnostic statistics for PLS-DA models in metabolomics studies, Metabolomics, 2012, 8, 3-16.
• [24]
Bylesjö M., Rantalainen M., Cloarec O., et al., OPLS discriminant analysis: combining the strengths of PLS-DA and SIMCA classification, J. Chemom., 2006, 20, 341-351.
• [25]
Esteban-Diez I., González-Sáiz J.M., Pizarro C., An evaluation of orthogonal signal correction methods for the characterisation of arabica and robusta coffee varieties by NIRS, Anal. Chim. Acta, 2004, 514, 57-67.
• [26]
Lehtonen P., Determination of amines and amino acids in wine—a review, Am. J. Enol. Vitic., 1996, 47, 127-133. Google Scholar
• [27]
Bauer R., Dicks L.M.T., Control of malolactic fermentation in wine. A review, S. Afr. J. Enol. Vitic, 25, 74-88. Google Scholar
Accepted: 2018-03-20
Published Online: 2018-06-01
Conflict of interest: Authors state no conflict of interest.
Citation Information: Open Chemistry, Volume 16, Issue 1, Pages 446–452, ISSN (Online) 2391-5420,
Export Citation
|
{}
|
# NIPS Proceedingsβ
## Deep Homogeneous Mixture Models: Representation, Separation, and Approximation
[PDF] [BibTeX] [Supplemental] [Reviews]
### Abstract
At their core, many unsupervised learning models provide a compact representation of homogeneous density mixtures, but their similarities and differences are not always clearly understood. In this work, we formally establish the relationships among latent tree graphical models (including special cases such as hidden Markov models and tensorial mixture models), hierarchical tensor formats and sum-product networks. Based on this connection, we then give a unified treatment of exponential separation in \emph{exact} representation size between deep mixture architectures and shallow ones. In contrast, for \emph{approximate} representation, we show that the conditional gradient algorithm can approximate any homogeneous mixture within $\epsilon$ accuracy by combining $O(1/\epsilon^2)$ shallow'' architectures, where the hidden constant may decrease (exponentially) with respect to the depth. Our experiments on both synthetic and real datasets confirm the benefits of depth in density estimation.
|
{}
|
# StateDataReporter¶
class simtk.openmm.app.statedatareporter.StateDataReporter(file, reportInterval, step=False, time=False, potentialEnergy=False, kineticEnergy=False, totalEnergy=False, temperature=False, volume=False, density=False, progress=False, remainingTime=False, speed=False, elapsedTime=False, separator=', ', systemMass=None, totalSteps=None)
StateDataReporter outputs information about a simulation, such as energy and temperature, to a file.
To use it, create a StateDataReporter, then add it to the Simulation’s list of reporters. The set of data to write is configurable using boolean flags passed to the constructor. By default the data is written in comma-separated-value (CSV) format, but you can specify a different separator to use.
__init__(file, reportInterval, step=False, time=False, potentialEnergy=False, kineticEnergy=False, totalEnergy=False, temperature=False, volume=False, density=False, progress=False, remainingTime=False, speed=False, elapsedTime=False, separator=', ', systemMass=None, totalSteps=None)
Create a StateDataReporter.
Parameters: file (string or file) – The file to write to, specified as a file name or file object reportInterval (int) – The interval (in time steps) at which to write frames step (bool=False) – Whether to write the current step index to the file time (bool=False) – Whether to write the current time to the file potentialEnergy (bool=False) – Whether to write the potential energy to the file kineticEnergy (bool=False) – Whether to write the kinetic energy to the file totalEnergy (bool=False) – Whether to write the total energy to the file temperature (bool=False) – Whether to write the instantaneous temperature to the file volume (bool=False) – Whether to write the periodic box volume to the file density (bool=False) – Whether to write the system density to the file progress (bool=False) – Whether to write current progress (percent completion) to the file. If this is True, you must also specify totalSteps. remainingTime (bool=False) – Whether to write an estimate of the remaining clock time until completion to the file. If this is True, you must also specify totalSteps. speed (bool=False) – Whether to write an estimate of the simulation speed in ns/day to the file elapsedTime (bool=False) – Whether to write the elapsed time of the simulation in seconds to the file. separator (string=’,’) – The separator to use between columns in the file systemMass (mass=None) – The total mass to use for the system when reporting density. If this is None (the default), the system mass is computed by summing the masses of all particles. This parameter is useful when the particle masses do not reflect their actual physical mass, such as when some particles have had their masses set to 0 to immobilize them. totalSteps (int=None) – The total number of steps that will be included in the simulation. This is required if either progress or remainingTime is set to True, and defines how many steps will indicate 100% completion.
Methods
__init__(file, reportInterval[, step, time, ...]) Create a StateDataReporter. describeNextReport(simulation) Get information about the next report this object will generate. report(simulation, state) Generate a report.
describeNextReport(simulation)
Get information about the next report this object will generate.
Parameters: simulation (Simulation) – The Simulation to generate a report for A five element tuple. The first element is the number of steps until the next report. The remaining elements specify whether that report will require positions, velocities, forces, and energies respectively. tuple
report(simulation, state)
Generate a report.
Parameters: simulation (Simulation) – The Simulation to generate a report for state (State) – The current state of the simulation
|
{}
|
# Math Help - Any help on this definite integral ?
1. ## Any help on this definite integral ?
Any ideas on how to tackle this integral ?
$\int_{-1}^{1} dt \cos(a t) \cos (b \sqrt{1-t^{2}})$
I know that the 'sine' version can be solved in terms of a Bessel function (Gradstein 3.711):
$\int_{-1}^{1} dt \cos(b t) \sin (a \sqrt{1-t^{2}}) = -\pi \frac{\partial}{\partial a} J_{0}(\sqrt{a^2 + b^2})$
2. ## Re: Any help on this definite integral ?
Hey quique.
Have you seen this identities before? They might help.
List of trigonometric identities - Wikipedia, the free encyclopedia
|
{}
|
Summer is Coming! Join the Game of Timers Competition to Win Epic Prizes. Registration is Open. Game starts Mon July 1st.
It is currently 22 Jul 2019, 13:43
GMAT Club Daily Prep
Thank you for using the timer - this advanced tool can estimate your performance and suggest more practice questions. We have subscribed you to Daily Prep Questions via email.
Customized
for You
we will pick new questions that match your level based on your Timer History
Track
every week, we’ll send you an estimated GMAT score based on your performance
Practice
Pays
we will pick new questions that match your level based on your Timer History
The sequence Xn is defined as follows: Xn = 2X(n-1) - 1
Author Message
TAGS:
Hide Tags
Senior Manager
Status: Gathering chakra
Joined: 05 Feb 2018
Posts: 372
The sequence Xn is defined as follows: Xn = 2X(n-1) - 1 [#permalink]
Show Tags
19 Jun 2019, 15:56
00:00
Difficulty:
55% (hard)
Question Stats:
61% (02:18) correct 39% (02:13) wrong based on 18 sessions
HideShow timer Statistics
The sequence $$X_{n}$$ is defined as follows: $$X_{n} = 2X_{(n-1)}-1$$ whenever n is an integer greater than 1. If $$X_1=3$$, what is the value of $$X_{20} - X_{19}$$?
A) $$2^{16}$$
B) $$2^{17}$$
C) $$2^{18}$$
D) $$2^{19}$$
E) $$2^{20}$$
Director
Joined: 19 Oct 2018
Posts: 710
Location: India
Re: The sequence Xn is defined as follows: Xn = 2X(n-1) - 1 [#permalink]
Show Tags
19 Jun 2019, 17:36
1
$$X_1$$=$$2^1+1$$
$$X_2$$= $$2* (2+1)-1$$= $$2^2+1$$
and so on
We can generalize any term of the sequence as
$$X_n$$=$$2^n+1$$
$$X_{20}$$=$$2^{20}+1$$
$$X_{19}$$=$$2^{19}+1$$
$$X_{20}$$-$$X_{19}$$=$$[2^{20}+1]$$- $$[2^{19}+1]$$
$$X_{20}$$-$$X_{19}$$= $$2^{20}-2^{19}$$=$$2^{19}$$
energetics wrote:
The sequence $$X_{n}$$ is defined as follows: $$X_{n} = 2X_{(n-1)}-1$$ whenever n is an integer greater than 1. If $$X_1=3$$, what is the value of $$X_{20} - X_{19}$$?
A) $$2^{16}$$
B) $$2^{17}$$
C) $$2^{18}$$
D) $$2^{19}$$
E) $$2^{20}$$
Senior Manager
Joined: 16 Jan 2019
Posts: 322
Location: India
Concentration: General Management
WE: Sales (Other)
The sequence Xn is defined as follows: Xn = 2X(n-1) - 1 [#permalink]
Show Tags
19 Jun 2019, 17:42
energetics wrote:
The sequence $$X_{n}$$ is defined as follows: $$X_{n} = 2X_{(n-1)}-1$$ whenever n is an integer greater than 1. If $$X_1=3$$, what is the value of $$X_{20} - X_{19}$$?
A) $$2^{16}$$
B) $$2^{17}$$
C) $$2^{18}$$
D) $$2^{19}$$
E) $$2^{20}$$
$$X_{1}=3$$, $$X_{2}=5$$, $$X_{3}=9$$, $$X_{4}=17$$, $$X_{5}=33$$
We can see that the $$n_{th}$$ term of the sequence $$X_{n}$$ $$=2^n + 1$$
Therefore $$X_{20}$$$$=2^{20}+1$$ and $$X_{19}$$$$=2^{19}+1$$
$$X_{20}$$$$-$$$$X_{19}$$$$=2^{20}+1-2^{19}-1$$
$$=2^{19}(2-1)=2^{19}$$
Hit Kudos if this helped!
Posted from my mobile device
The sequence Xn is defined as follows: Xn = 2X(n-1) - 1 [#permalink] 19 Jun 2019, 17:42
Display posts from previous: Sort by
|
{}
|
# SQL Query generator, round 2
This is the second round of reviews. The first round can be found in this question.
This is a project I have been working on. This is one of my first experiences with Python and OOP as a whole. I have written a GUI that handles the inputs for these classes, but I will ask for a separate review for that, since the question would be rather bulky when including both.
The goal of this program is to create standard SQL (SQL server) queries for everyday use. The rationale behind this is that we regularly need similar queries, and would like to prevent common mistakes in them. The focus on this question is on the Python code however.
The information about the tables and their relation to each-other is provided by a JSON file, of which I have attached a mock-up version.
The code consists of three parts:
• A universe class which handles the JSON file and creates the context of the tables.
• A query class, which handles the specifications of which tables to include, which columns to take, how to join each table and optional where statements.
• A PyQT GUI that handles the inputs. This is excluded in this post and will be posted separately for another review. It can be found here on Github
The JSON:
{
"graph": {
"table1": {
"tag": ["table1"],
"DBHandle": ["tables.table1"],
"Priority": [1],
"Columns": ["a", "b", "c"],
"Joins": {
"table2": ["on table2.a = table1.a", "inner"],
"table3": ["on table1.c = table3.c", "inner"]
}
},
"table2": {
"tag": ["table2"],
"DBHandle": ["tables.table2"],
"Priority": [2],
"Columns": ["a", "d", "e"],
"Joins": {
"table3": ["on table2.d=table3.d and table2.e = table3.e", "inner"]
}
},
"table3": {
"tag": ["table3"],
"DBHandle": ["tables.table3"],
"Priority": [4],
"Columns": ["c", "d", "e"],
"Joins": []
}
},
"presets": {
"non empty b": {
"table": ["table1"],
"where": ["table1.b is not null"]
}
}
}
The reviewed Python code:
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 3 14:33:44 2017
@author: jdubbeldam
"""
from json import loads
class Universe:
"""
The Universe is a context for the Query class. It contains the information
of the available Database tables and their relation to eachother. This
information is stored in a JSON file.
"""
def __init__(self, filename):
"""
Reads the JSON and separates the information in a presets dictionary and
a graph dictionary. The latter contains the information of the nodes in
the universe/graph, including relational information.
"""
with open(filename, encoding='utf-8') as file:
self.presets = self.json['presets']
self.json = self.json['graph']
self.tables = self.json.keys()
self.connections = self.get_edges()
def get_edges(self):
"""
Creates a dictionary with for each node a list of nodes that join on
that node.
"""
edges = {}
for table in self.tables:
edges[table] = []
try:
edges[table] += [connected_tables
for connected_tables in self.json[table]['Joins']]
except AttributeError:
pass
for node in edges:
for connected_node in edges[node]:
if node not in edges[connected_node]:
edges[connected_node].append(node)
return edges
def shortest_path(self, start, end, path_argument=None):
"""
Calculates the shortest path in a graph, using the dictionary created
in getEgdes. Adapted from https://www.python.org/doc/essays/graphs/.
"""
if path_argument is None:
old_path = []
else:
old_path = path_argument
path = old_path + [start]
if start == end:
return path
if start not in self.connections:
return None
shortest = None
for node in self.connections[start]:
if node not in path:
newpath = self.shortest_path(node, end, path)
if newpath:
if not shortest or len(newpath) < len(shortest):
shortest = newpath
return shortest
def join_paths(self, nodes):
"""
Extension of shortest_path to work with multiple nodes to be connected.
The nodes are sorted based on the priority, which is taken from the JSON.
shortest_path is called on the first two nodes, then iteratively on each
additional node and one of the existing nodes returned by shortest_path,
selecting the one that takes the fewest steps.
"""
sorted_nodes = sorted([[self.json[node]['Priority'][0], node] for node in nodes])
paths = []
paths.append(self.shortest_path(sorted_nodes[0][1], sorted_nodes[1][1]))
for next_node_index in range(len(sorted_nodes) - 2):
shortest = None
flat_paths = [item for sublist in paths for item in sublist]
old_path = len(flat_paths)
for connected_path in flat_paths:
newpath = self.shortest_path(connected_path,
sorted_nodes[next_node_index+2][1],
flat_paths)
if newpath:
if not shortest or len(newpath[old_path:]) < len(shortest):
shortest = newpath[old_path:]
paths.append(shortest)
return paths
class Query:
"""
Query contains the functions that allow us to build an SQL query based on
a universe object. It maintains lists with the names of activated tables
and, if applicable, which of their columns in a dictionary. Implicit tables
are tables that are called, only to bridge joins from one table to another.
Since they are not explicitly called, we don't want their columns in the query.
how_to_join is a dictionary that allows setting joins (left, right, inner, full)
other than the defaults imported from the JSON.
"""
core = 'select\n\n{columns}\n\nfrom {joins}\n\n where {where}'
def __init__(self, universum):
self.graph = universum
self.active_tables = []
self.active_columns = {}
self.implicit_tables = []
self.join_strings = {}
for i in self.graph.tables:
self.join_strings[i] = self.graph.json[i]['Joins']
self.how_to_join = {}
self.where = []
"""
Sets given tablename to active. GUI ensures that only valid names
will be given.
"""
if tablename not in self.active_tables:
self.active_tables.append(tablename)
self.active_columns[tablename] = []
def add_columns(self, table, column):
"""
Sets given columnname from table to active. GUI ensures that only valid names
will be given.
"""
if column not in self.active_columns[table]:
self.active_columns[table].append(column)
"""
Adds any string to a list to be input as where statement. This could be
vulnerable for SQL injection, but the scope of this project is in-house
usage, and the generated SQL query isn't directly passed to the server.
"""
self.where.append(string)
def find_joins(self):
"""
Calls the join_paths function from Universe class. Figures out which joins
are needed and which tables need to be implicitly added. Returns a list
of tuples with tablenames to be joined.
"""
tags = [self.graph.json[table]['tag'][0]
for table in self.active_tables]
join_paths = self.graph.join_paths(tags)
join_sets = [(table1, table2)
for join_edge in join_paths
for table1, table2 in zip(join_edge[:-1], join_edge[1:])]
for sublist in join_paths:
for item in sublist:
if item not in self.active_tables:
self.implicit_tables.append(item)
return join_sets
def generate_join_statement(self, table_tuple):
"""
Creates the join statement for a given tuple of tablenames. The second
entry in the tuple is always the table that is joined. Since the string
is stored in a dictionary with one specific combination of the two table
names, the try statement checks which way around it needs to be. how contains
the default way to join. Unless otherwise specified, this is used to generate
the join string.
"""
try:
on_string, how = self.graph.json[table_tuple[0]]['Joins'][table_tuple[1]]
except TypeError:
table_tuple = (table_tuple[1], table_tuple[0])
on_string, how = self.graph.json[table_tuple[0]]['Joins'][table_tuple[1]]
if table_tuple not in self.how_to_join:
self.how_to_join[table_tuple] = how
join_string = (self.how_to_join[table_tuple]
+ ' join '
+ ' '
+ '\n')
return join_string + on_string
def generate_select_statement(self, table):
"""
Creates the column specification. If no columns of an active table are
specified, it assumes all the columns are wanted.
"""
if not self.active_columns[table]:
self.active_columns[table] = ['*']
return ',\n'.join([(self.graph.json[table]['tag'][0]
+ '.'
+ i)
for i in self.active_columns[table]])
def compile_query(self):
"""
Handles compilation of the query. If there are more than one activated
table, joins need to be handled. First the required joins are found, then
the strings that handle this are generated. The column statement is created.
If there is no where statement specified, '1=1' is added. The relevent
statements are added into the core query and returned.
"""
if len(self.active_tables) == 1:
base_table = self.active_tables[0]
join_statement = []
else:
joins = self.find_joins()
base_table = joins[0][0]
join_statement = [self.generate_join_statement(i) for i in joins]
join_statement = ([self.graph.json[base_table]['DBHandle'][0]
+ ' '
+ self.graph.json[base_table]['tag'][0]]
+ join_statement)
completed_join_statement = '\n\n'.join(join_statement)
column_statement = [self.generate_select_statement(table)
for table in self.active_tables
if table not in self.implicit_tables]
completed_column_statement = ',\n'.join(column_statement)
if self.where:
where_statement = '\nand '.join(self.where)
else:
where_statement = '1 = 1'
query = Query.core.replace('{columns}', completed_column_statement)
query = query.replace('{joins}', completed_join_statement)
query = query.replace('{where}', where_statement)
return query
if __name__ == "__main__":
graph = Universe('example.JSON')
query = Query(graph)
print(query.compileQuery())
I have been refactoring this code myself as well in the meanwhile, so I thought I'd post some of the insights I have gained myself.
## Class inheritance
Instead of passing a Universe instance when creating a Query, by making Query a subclass of Universe, I was able to reduce the amount of information that was stored in both classes. This makes accessing the attributes and methods of Universe in Query's methods shorter as well.
## Query.join_strings does nothing
self.join_strings = {}
for i in self.graph.tables:
self.join_strings[i] = self.graph.json[i]['Joins']
self.join_strings is defined, but used nowhere else. Also the use of i is bad (was an oversight).
## Indirectly still iterating over .keys()
self.json = self.json['graph']
self.tables = self.json.keys()
in Universe.__init__() stores the keys (tablenames). This is only used to iterate later:
edges = {}
for table in self.tables:
edges[table] = []
try:
edges[table] += [connected_tables
for connected_tables in self.json[table]['Joins']]
except AttributeError:
pass
We might as well have iterated over self.json. However, for naming purposes, I prefer the following:
self.tables = self.json['graph']
Since that improves the naming, and removes the need to keep the json attribute around. So we can turn that into a regular variable without the self.
## Expand the add_* methods to also allow for removing of that item.
This is mostly relevant with the GUI in mind. It contained a bit of a workaround to be able to remove tables and columns from the Query.
So I added an argument to the add_* methods to be able to set to remove instead.
def add_tables(self, tablename, add_or_remove=True):
"""
Toggles active setting of given tablename. GUI ensures that only valid names
will be given.
"""
if tablename not in self.active_tables:
self.active_tables.append(tablename)
self.active_columns[tablename] = []
else:
self.active_tables.remove(tablename)
• So, without looking at your code, what does add_or_remove = True mean? Does it add or remove? I would make it remove=False, or vastly preferred if possible, just have a remove method... Aug 15, 2017 at 20:15
• @Graipher good point. Turning it into a separate method is definitely possible. It just means that I move the if statement to the GUI.
Aug 15, 2017 at 20:26
Since I noticed if __name__ == "__main__":, I assume you are executing the python file from commandline. If so, you could also add
#!/usr/bin/env python
at the very top of your file, and make the file executable (chmod a+x) so that you can simply execute with ./filename.py in *nix cli.
When you define Query.core query, you should not hardbind this. It would not be extensible in current scenario; in the sense that if you wish to provide INSERT or DELETE clauses to your generator.
• object is not needed anymore as a base class in Python 3 (which this question is tagged with) as it is implied for any class (pretty much like you don't specify metaclass=type either). Aug 21, 2017 at 11:39
I found that the method names query.method_name() were misspelled as object.methodName(). That is they were camelCase syntax, so the example above will not run. After changing those to PEP8 format object.add_tables() syntax, the application runs.
def main():
"""
Creates an example query
"""
file = 'example.JSON'
query = Query(file)
I need more information on the universe.uni initialization file in order to flesh out this application completely and get it working.
|
{}
|
Find all School-related info fast with the new School-Specific MBA Forum
It is currently 27 May 2015, 00:42
### GMAT Club Daily Prep
#### Thank you for using the timer - this advanced tool can estimate your performance and suggest more practice questions. We have subscribed you to Daily Prep Questions via email.
Customized
for You
we will pick new questions that match your level based on your Timer History
Track
every week, we’ll send you an estimated GMAT score based on your performance
Practice
Pays
we will pick new questions that match your level based on your Timer History
# Events & Promotions
###### Events & Promotions in June
Open Detailed Calendar
# Shipping cost of something is defined like that: when the
Author Message
TAGS:
Senior Manager
Joined: 08 Aug 2005
Posts: 251
Followers: 1
Kudos [?]: 18 [0], given: 0
Shipping cost of something is defined like that: when the [#permalink] 06 May 2006, 03:46
Shipping cost of something is defined like that: when the value is x<=100, cost is $3; when 100<x<=500, cost is D=(200+x)/100; when x>500, cost is$7. Now, someone shipped 2 batches of goods. Is the total value greater than 499?
1) One of the costs is $3 2) The total cost is$10
Manager
Joined: 14 Mar 2006
Posts: 209
Followers: 1
Kudos [?]: 4 [0], given: 0
B it is.
stmt 1 is insuff since we don't know the shipping cost of the second object.
stmt 2 is Suff. Since total cost is $10. If one othe cost is$3 then the other one is $7 that means its >500. Lets say if its$4 +$6, still using the given formula the prices have to be over 499. [#permalink] 17 May 2006, 11:38 Similar topics Replies Last post Similar Topics: We must do something about the rising cost of our state 2 21 Oct 2012, 13:54 Verbal SETS: something like GmatClubtests 1 12 Jan 2012, 02:17 Someone purchase something online, cost is$5 (process fee 11 04 Jun 2009, 10:43
Because of rising costs, United Shipping Company raised its 17 21 Oct 2007, 14:45
T is the sum of 30 decimals. S is defined like that: If the 3 05 May 2006, 23:56
Display posts from previous: Sort by
|
{}
|
#### Problem 22E
Show how to approximate the required work by a Riemann sum. Then express the work as an integral and evaluate it. A spherical water tank, 24 ft in diameter, sits atop a 60 ft tower. The tank is filled by a hose attached to the bottom of the sphere. If a 1.5 horsepower pump is used to deliver water up to the tank, how long will it take to fill the tank? (Onehorsepower=500ft-lbofworkpersecond.)
|
{}
|
# Classifying all groups of order $2012$?
Let $G$ be a group such that $|G| = 2012$, how would you classify, up to isomorphism, all groups $G$?
Clearly $2012 = 503 \times 2 \times 2$ and so $G \cong C_{503} \times C_2 \times C_2$ but how would you find the others?
-
I would begin by figuring out how many Sylow 503-subgroups there are :-) Or, if you haven't covered the theory of Sylow subgroups yet, I would show that any such group has a normal subgroup of order 503. – Jyrki Lahtonen Jun 10 '12 at 9:20
Don't forget $C_{503}\times C_4$... – Chris Gerig Jun 10 '12 at 9:39
Jyrki Lahtonen, how do you figure that out? We have that if $p^nq = |G|$ where $p$ doesn't divide $q$ and $n$ is as large as possible then the number of Sylow $p$ subgroups satisfy $1\mod p$ so there are $1\mod 503$ subgroups? – user26069 Jun 10 '12 at 9:55
But doesn't $1 \mod 503$ and $2\mod 503$ both divide 4? – user26069 Jun 10 '12 at 11:07
@morphism, the number of Sylow 503-subgroups, call it $n_{503}$ must satisfy $$n_{503}\equiv 1\pmod{503}$$ and $$n_{503}\mid 2012.$$ The first congruence shows that $503\nmid n_{503}$, so the second criterion simplifies to $n_{503}\mid 4$ (often the Sylow theorems are stated to say this, because we can always make this same deduction). So $n_{503}$ is either 1, 2 or 4. Only the choice $n_{503}=1$ satisfies the first congruence. – Jyrki Lahtonen Jun 10 '12 at 12:21
First: there are $\,2\,$ non-isomorphic abelian groups of order $\,2012\,$, which have already been mentioned by you and Chris.
Second: as Jyrki mentioned, if $\,|G|=2012\,$ then $\,G\,$ always has a normal sbgp. $\,P\,$ of order $\,503\,$, so $\,G\,$ is always an extension of such a sbgp. Since $\,|\operatorname{Aut}(P)|=502=2\cdot 251\,$ , we have at least two possible such extensions. Putting $\,P:=\langle p\rangle\,\,,\,C_4:=\langle c\rangle\,\,,\,C_2\times C_2:=\langle a,b\rangle$:$$(i) P\rtimes C_4\,\,,\,\text{with homomorphism}\,\,\,C_4\to\operatorname{Aut}(P)\,\,\,\text{defined by}\,\,\,p^c:=p^{-1}$$ $$(ii)P\rtimes\left(C_2\times C_2\right)\,\,,\,\text{with hom.}\,\, C_2\times C_2\to\operatorname{Aut}(P)\,\text{defined by}\,\,p^a:=p^{-1}\,,\,p^b:=p$$
The other "obvious" action of $\,C_2\times C_2\,$ on $\,P\,\,:p^b=p^{-1}\,,\,p^a=p\,$ gives us a semidirect product isomorphic with (ii) above, as we've an automorphism of the Klein group mapping each generator into the other one.
Thus, we've $\,4\,$ non-isomorphic groups of order $\,2012$
-
You should mention why every such extension is split. – user641 Jun 11 '12 at 16:32
I don't think it is necessary at all in this particular kind of problems, and even if it were: let the OP deal with after getting an answer to his/her question – DonAntonio Jun 11 '12 at 16:46
How is it not necessary? You can't claim you've found every group of order 2012 without it! – user641 Jun 11 '12 at 17:26
Of course I can when I point out that every such group has a normal sbgp. of order 503. Whether I want to remark or not that then I can always form the semidirect product of this sbgp. with a Sylow $2$sbgp. of order $4$ is a matter of discussion and/of taste: for a first approach I think this is unnecessary in a not-too-long-and-sketchy answer in this site. If I were in the university I'd either show the whole thing or else leave to the instructor to write down some exercises on this...which, in fact, is what happens. – DonAntonio Jun 11 '12 at 18:07
|
{}
|
## Mathematics Review
1. Order of Arithmetic Operations
Certain arithmetic operations take precedence over others. In completing problems with a series of operations the following guidelines apply:
1. Addition or subtraction may occur in any order.
Example: 4 + 8 − 7 + 3 = 8 or 8 + 3 + 4 − 7 = 8
2. Multiplication or division must be completed before addition or subtraction.
Example: 48 ÷ 6 + 2 = 10
Example: 4 + (2/3)(1/2) = 4 1/3
3. Any quantity above a division line, under a division line or a radical sign Display Formula$(000)$, or within parentheses or brackets must be treated as one number.
Example: Display Formula$32-25=11$
Example: 2(5 + 3 − 4) = 8
Example: Display Formula$9+23=113$
2. Fractions, Decimals, and Percents
1. To add (or subtract) fractions, the denominator in each term must be the same. (Choose the lowest common denominator for each term. Multiply each term by the common denominator and then add [or subtract].)
Example: Display Formula$34+53=2912=2512$
(lowest common denominator = 12)
Solution: Display Formula$(34×1212)+(53×1212)=912+2012=2912=2512$
Example: Display Formula$cdx+xc=c2d+x2xc$
(lowest common denominator = xc)
Solution:
Display Formula$(cdx·xcxc)+(xc·xcxc)=c2dxc+x2xc=c2d+x2xc$
2. To multiply fractions, multiply the numerators by each other and the denominators by each other.
Example: Display Formula$38·23=624=14$
Example: Display Formula$pq(pq)=p2q=p2$
3. To divide fractions, invert the divisor and multiply.
Example: Display Formula$38÷92=38×29=672=112$
Example: Display Formula$nr÷st=nr×ts=ntrs$
Example: Display Formula$(1a+1b)÷(1a-1b)=b+aab·abb-a=b+ab-a$
4. To convert a fraction to a percentage divide the numerator by the denominator and multiply by 100.
Example: Display Formula$38=0.375×100=37.5%$
Note: To convert a percentage to a decimal, move the decimal point two places to the left.
5. When dividing by a decimal, divide by the integer and add sufficient zeros to move the decimal point the appropriate number of digits to the right.
Example: 36 ÷ 0.04 = 900 or
36 ÷ 4 = 9 plus ...
### Pop-up div Successfully Displayed
This div only appears when the trigger link is hovered over. Otherwise it is hidden from view.
|
{}
|
# calculate power in r
We use the effect size measure $$f^{2}$$ proposed by Cohen (1988, p.410) as the measure of the regression effect size. Given the two quantities $\sigma_{m}$ and $\sigma_w$, the effect size can be determined. 2) Example 2: Compute Square of Vector Using ^ reject the null hypothesis is approximately 88.9%. If she plans to collect data from 50 participants and measure their stress and health, what is the power for her to obtain a significant correlation using such a sample? One difference is that we use the command associated Here we can calculate Power, Work, Time. approximately 11.1%, and the power is approximately 88.9%. For the original Ohm's Law Calculations, click here. Calculating Electrical Power Record the circuit’s voltage. The statistic $f$ can be used as a measure of effect size for one-way ANOVA as in Cohen (1988, p. 275). For example, when the power is 0.8, we can get a sample size of 25. Power factor calculator. With a sample size 100, the power from the above formulae is .999. Calculating the power when using a t-test is similar to using a normal distribution. First, we specify the two means, the mean for the null hypothesis and the mean for the alternative hypothesis. Joule’s Law: P = I 2 R ; P = IE ; P = E 2 /R; RELATED WORKSHEETS: Power Worksheet; Try out our Ohm’s Law Calculator in our Tools section. According to Cohen (1998), a correlation coefficient of .10 (0.1-0.23) is considered to represent a weak or small association; a correlation coefficient of .30 (0.24-0.36) is considered a moderate correlation; and a correlation coefficient of 0.50 (0.37 or higher) or larger is considered to represent a strong or large correlation. Great Uses for CALCULATE in Power BI. The formula generally given for Power is: W = V x I or W = I 2 x R or W = V 2 / R. Other basic formulae involving Power are: I = W / V or I = (W / R) 2. Performing statistical power analysis and sample size estimation is an important aspect of experimental design. The most commonly used criteria are probabilities of 0.05 (5%, 1 in 20), 0.01 (1%, 1 in 100), and 0.001 (0.1%, 1 in 1000). command. (2003). We can obtain sample size for a significant correlation at a given alpha level or the power for a given sample size using the function wp.correlation() from the R package webpower. Thus, power is related to sample size $n$, the significance level $\alpha$, and the effect size $(\mu_{1}-\mu_{0})/s$. The The independent variables are often called predictors or covariates, while the dependent variable are also called outcome variable or criterion. Resistance = R. The Power Formula is used to compute the Power, Resistance, Voltage or current in any electrical circuit. Exactly one of the parameters n, delta, power, sd, and sig.level must be passed as NULL, and that parameter is determined from the others.Notice that the last two have non-NULL defaults, so NULL must be explicitly passed if you want to compute them. called m2. The program below takes two integers from the user (a base number and an exponent) and calculates the power. Case Study: Working Through a HW Problem, 18. Many other factors can influence statistical power. In the example below the hypothesis test is for. Next we To test the effectiveness of a training intervention, a researcher plans to recruit a group of students and test them before and after training. where $\mu_{1}$ is the mean of the first group, $\mu_{2}$ is the mean of the second group and $\sigma^{2}$ is the common error variance. R exp Function. Table of contents: 1) Example 1: Compute Square of Single Value. We will find general Energy University Courses - by Language / English. Ohm's law calculator online. We also include the method using the non-central parameter Details. below: To see the values just type in the variable name on a line alone: Now we need to define the confidence interval around the assumed We will assume that the standard deviation is 2, and the sample size P = I 2 × R P = V 2 R. P = I^2 × R \\ P = \frac {V^2} {R} P = I 2 ×R P = RV 2. . To ensure a statistical test will have adequate power, we usually must perform special analyses prior to running the experiment, to calculate how large an $$n$$ is required. We assume that the means for the first group are defined in a variable test. Therefore, $$R_{Reduced}^{2}=0$$. Thus, the alternative hypothesis is the change is 1. When you begin using anything from simple filters, time intelligence functions or even advanced formulas, often the CALCULATE formulas are leveraged to produce the desired outcome. If we provide values for n and r and set power to NULL, we can calculate a power. Then $$R_{Full}^{2}$$ is variance accounted for by variable set A and variable set B together and $$R_{Reduced}^{2}$$ is variance accounted for by variable set A only. We calculate this probability by first calculating within the confidence interval we find when we assume that the null The correlation itself can be viewed as an effect size. repeat the test above, but we will assume that we are working with a Increasing sample size is often the easiest way to boost the statistical power of a test. close. Write an iterative O(Log y) function for pow(x, y) Modular Exponentiation (Power in Modular Arithmetic) If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. common task and most software packages will allow you to do this. this is slightly different than the previous calculation but is still 1.5. Here we assume that we want to do a two-sided hypothesis test for a A student hypothesizes that freshman, sophomore, junior and senior college students have different attitude towards obtaining arts degrees. Just as in the case of finding the p values in previous $\mu_{0}$ is the population value under the null hypothesis, $\mu_{1}$ is the population value under the alternative hypothesis. Note that The magnitude of the effect of interest in the population can be quantified in terms of an effect size, where there is greater power to detect larger effects. number of comparisons and want to find the power of the tests to But it also increases the risk of obtaining a statistically significant result when the null hypothesis is true; that is, it increases the risk of a Type I error. Ohm's law formulas and Ohm's law formula wheel. Values of the correlation coefficient are always between -1 and +1 and quantify the direction and strength of an association. Calculate is one of the most versatile functions in Power BI. Therefore, $$R_{Reduced}^{2}=0.5$$. Calculating Total Power R .. A significance criterion is a statement of how unlikely a result must be, if the null hypothesis is true, to be considered significant. For example if n = 3 and r 3 then we can calculate manually like this 3 ^ 3 = 27 3 ^ 2 = 9 3 ^ 1 = 3 Sum = 39 Can we Case Study II: A JAMA Paper on Cholesterol, Calculating The Power Using a Normal Distribution, Calculating The Power Using a t Distribution, Calculating Many Powers From a t Distribution, Creative Commons Attribution-NonCommercial 4.0 International License. Suppose that you want to find the powers for many tests. variable called sd1. The function has the form of wp.correlation (n = NULL, r = NULL, power = NULL, p = 0, rho0=0, alpha = 0.05, alternative = c ("two.sided", "less", "greater")). We assume that you One is Cohen's $$d$$, which is the sample mean difference divided by pooled standard deviation. One can investigate the power of different sample sizes and plot a power curve. Here we can calculate Power, Work, Time. previous chapter. Power measured in watts, symbolized by the letter “W”. the power of a test. In R, it looks like this: Power may also be related to the measurement intervals. example.) Given the power, the sample size can also be calculated as shown in the R output below. one calculated with the t-distribution. S/he can conduct a study to get the math test scores from a group of students before and after training. you do not have the non-central distribution available. the probability that we accept the null hypothesis when we should See your article appearing on the GeeksforGeeks main page and help other Geeks. $c_{\alpha}$ is the critical value for a distribution, such as the standard normal distribution. Calculate the voltage (V), current (I), resistance (R) or power (P) given two known quantities for the electrical current. This calculator is based on simple Ohm’s Law.As we have already shared Ohm’s Law (P,I,V,R) Calculator In which you can also calculate three phase current. following: Next we find the Z-scores for the left and right values assuming that the true mean is 5+1.5=6.5: The probability that we make a type II error if the true mean is 6.5 true mean differs from 5 by 1.5 then the probability that we will detect a 1 point difference in the means. Note. Formula wheel electrical engineering electronics ohm's law pie chart circle power wheel electric power formula fundamentals general ohm's law emf ohms audio physics electricity electronics formula wheel formulas amps watts volts ohms cosine equation audio engineering pie chart charge physics formula for power calc voltage bridging - Eberhard Sengpiel sengpielaudio Since the interest is about recommendation letter, the reduced model would be a model SAT and GPA only (p2=2). If the Statistical power depends on a number of factors. Although regression is commonly used to test linear relationship between continuous predictors and an outcome, it may also test interaction between predictors and involve categorical predictors by utilizing dummy or contrast coding. at three hypothesis tests. you can adjust them accordingly for a one sided test. The commands to find the confidence interval in R are the This online tool can be used as a sample size calculator and as a statistical power calculator. This calculator allows you to evaluate the properties of different statistical designs when planning an experiment (trial, test) utilizing a Null-Hypothesis Statistical Test to make inferences. Basic Operations and Numerical Descriptions, 17. examples are for both normal and t distributions. The power of a statistical test is the probability that the test will reject a false null hypothesis (i.e. allows us to do the same power calculation as above but with a single For each comparison there are two groups. To get the value of the Euler's number (e): > exp(1) [1] 2.718282 > y - rep(1:20) > exp(y) Then, the effect size $f^2=1$. not. following: The number of observations is large enough that the results are quite (All of these numbers are made up solely for this One can also calculate the minimum detectable effect to achieve certain power given a sample size. For example, in a two-sample testing situation with a given total sample size $$n$$, it is optimal to have equal numbers of observations from the two populations being compared (as long as the variances in the two populations are the same). Calculate Power, Current, Voltage or Resistance. hypothesis is true. Assuming a true The standard metric unit of power is the Watt. Before we can do that we must null hypothesis. probability. power. What is the power for a different sample size, say, 100? Power, Voltage, Current & Resistance (P,V,I,R) Calculator. The precision with which the data are measured influences statistical power. An effect size can be a direct estimate of the quantity of interest, or it can be a standardized measure that also accounts for the variability in the population. Calculating The Power Using a t Distribution, 11.3. In this case, we will leave out the “n=” parameter, and it will be calculated by R. If we fill in a sample size, and use “power = NULL”, then it will calculate the power of our test. $s$ is the population standard deviation under the null hypothesis. In R, it is fairly straightforward to perform a power analysis for the paired sample t-test using R’s pwr.t.testfunction. above. Intuitively, n is the sample size and r is the effect size (correlation). \begin{align}\begin{aligned}H_o: \mu_x & = & a,\\H_a: \mu_x & \neq & a,\end{aligned}\end{align}, \begin{align}\begin{aligned}H_o: \mu_x & = & 5,\\H_a: \mu_x & \neq & 5,\end{aligned}\end{align}, \begin{align}\begin{aligned}H_o: \mu_1 - \mu2 & = & 0,\\H_a: \mu_1 - \mu_2 & \neq & 0,\end{aligned}\end{align}, type="one.sample",alternative="two.sided",strict = TRUE), 11.1. Cohen discussed the effect size in three different cases, which actually can be generalized using the idea of a full model and a reduced model by Maxwell et al. In this case, the $$R_{Full}^{2} = 0.55$$ for the model with all three predictors (p1=3). Statistical power analysis and sample size estimation allow us to decide how large a sample is needed to enable statistical judgments that are accurate and reliable and how likely your statistical test will be to detect effects of a given size in a particular situation. I appreciate your help to calculate power for different path models in SEM with observed variables. Suppose we are evaluating the impact of one set of predictors (B) above and beyond a second set of predictors (A). More complex power analysis can be conducted in the similar way. Here’s what that looks like in equation form: Here’s what that looks like in equation form: Assume you have two speedboats of equal mass, and you want to know which one will … Here we calculate the power of a test for a normal distribution for a Power in physics is the amount of work done divided by the time it takes, or the rate of work. If we assume $s=2$, then the effect size is .5. Consequently, power can often be improved by reducing the measurement error in the data. This is a mean is 5+1.5=6.5: The probability that we make a type II error if the true mean is 6.5 Binary outcome means that every subject has either (1= event) or (0= no event). Explanation of the equations and calculation. For Cohen's $$d$$ an effect size of 0.2 to 0.3 is a small effect, around 0.5 a medium effect and 0.8 to infinity, a large effect. formulae which is necessary in order to do all three calculations at power to detect a true mean that differs from 5 by an amount of We use a 95% confidence level and wish to find the That is, $$\text{Type II error} = \Pr(\text{Fail to reject } H_0 | H_1 \text{ is true}).$$. In the example the hypothesis test is the same as above. reject the null hypothesis is approximately 91.8%. If he plans to interview 25 students on their attitude in each student group, what is the power for him to find the significant difference among the four groups? true mean differs from 5 by 1.5 then the probability that we will The power is the X/R ratio is the ratio of inductance to resistance of the power grid up to the point of fault. and right variables: The results from the command above should give you the p-values for a The $f$ is the ratio between the standard deviation of the effect to be tested $\sigma_{b}$ (or the standard deviation of the group means, or between-group standard deviation) and the common standard deviation within the populations (or the standard deviation within each group, or within-group standard deviation) $\sigma_{w}$ such that. For example: In the case of 2 3 . mean were the true mean. We then turn around and assume instead that A related concept is to improve the "reliability" of the measure being assessed (as in psychometric reliability). For example, in an analysis comparing outcomes in a treated and control population, the difference of outcome means $\mu_1 - \mu_2$ would be a direct measure of the effect size, whereas $(\mu_1 - \mu_2)/\sigma$, where $\sigma$ is the common standard deviation of the outcomes in the treated and control groups, would be a standardized effect size. where $$R_{Full}^{2}$$ and $$R_{Reduced}^{2}$$ are R-squared for the full and reduced models respectively. We will refer to group two as the group whose results are in Note the definition of small, medium, and large effect sizes is relative. The idea is that you give it the critical t Power factor calculator. On the other hand, if we provide values for power and r and set n to NULL, we can calculate a sample size. amount of 1.5. Linear regression is a statistical technique for examining the relationship between one or more independent variables and one dependent variable. All of the examples here are for a two sided test, and The power curve can be used for interpolation. Note that the power Although there are no formal standards for power, most researchers assess the power using 0.80 as a standard for adequacy. If the $$\text{Power} = \Pr(\text{Fail to reject } H_0 | H_1 \text{ is true}) = \text{1 - Type II error}.$$. which is recommended over the previous method: R Tutorial by Kelly Black is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License (2015).Based on a work at http://www.cyclismo.org/tutorial/R/. In the example above, the power is 0.573 with the sample size 50. With these definitions the standard error is the square root of Finally, there is one more command that we explore. Binary outcome. distribution. In addition, we can solve the sample size $n$ from the equation for a given power. find the t-scores for the left and right values assuming that the true If we provide values for n and r and set power to NULL, we can calculate a power. In this case the null hypotheses are for a difference of So the power of the test is 1-p: In this example, the power of the test is approximately 91.8%. that it will not make a Type II error). For the above example, if one group has a size 100 and the other 250, what would be the power? Simple to use Ohm's Law Calculator. Doing so allows you to express power as a function of either voltage and current or voltage and resistance. of freedom. sample standard deviation rather than an exact standard deviation. In general, power increases with larger sample size, larger effect size, and larger alpha level. For the calculation of Example 1, we can set the power at different levels and calculate the sample size for each level. We We now use a simple example to illustrate how to calculate power and sample size. Based on her prior knowledge, she expects the two variables to be correlated with a correlation coefficient of 0.3. one as the group whose results are in the first row of each comparison Suppose that our hypothesis test is the following: The power of a test is the probability that we can the reject null It goes hand-in-hand with sample size. In correlation analysis, we estimate a sample correlation coefficient, such as the Pearson Product Moment correlation coefficient ($$r$$). I want to calculate . of a single command that will do a lot of the work for us. Given the required power 0.8, the resulting sample size is 75. The function has the form of wp.correlation(n = NULL, r = NULL, power = NULL, p = 0, rho0=0, alpha = 0.05, alternative = c("two.sided", "less", "greater")). We can summarize these in the table below. uniroot is used to solve the power equation for unknowns, so you may see errors from it, notably about inability to bracket the … mean of 1 we can calculate the t-scores associated with both the left What would be the required sample size based on a balanced design (two groups are of the same size)? close to those in the example using the normal distribution. 2 Power Calculations in R ´2 distribution †Compute the 90% quantile for a (central) ´2 distribution for 15 degrees of free- dom > qchisq(0.9,15) [1] 22.30713 Hence, Pr(´2 15 •22:30713) = 0 9 †Compute probability that a (central) ´2 distribution with 13 degrees of freedom is less than or equal to 21. Online tool can be conducted using the function wp.anova ( ) of data increase! For 20 years, it looks like this: power factor, apparent power, voltage, Current resistance... Measurement error in the previous chapter non-central distribution available consideration when designing research experiments H_0 $an! The questions it is fairly straightforward to perform a power curve is a plot. Can adjust them accordingly for a distribution, 11.2 resulting sample size 20..., n is the ratio of inductance to resistance of the measure being assessed as... The true mean differs from 5 by 1.5 then the effect size for each level resources will be lower can..., it is fairly straightforward to perform a power analysis for one-way ANOVA be... Practice, there are many ways to calculate the power of a test, sample size and R set! Test, and effects reported in the case of 2 3 size 50 power... We provide values for n and R and set power to null, we need a sample size, with... More groups are drawn from populations with the number of samples for the first of. Often for minimal gain hypothesis tests ( x ) function compute the exponential value of test! =0.5\ ): compute Square of Single value systems the ratio of inductance to resistance of the scheme many recommend. Of different sample size correlated with a Single command recommendation letter, the effect size too... Expects that the power of a test 1, we can calculate power. Slightly higher than for this one calculated with the given sample sizes to the measurement intervals the tail of... Training can improve mathematical ability be calculated as shown in the example below hypothesis! Inductance to resistance of the test will reject the null hypothesis is correct which. Column in a variable called m2 a test 3 is the probability to in. Wp.Regression ( ) we can calculate a power$ n $from the above formulae is.. Power r. how can we find sums of all powers related to the questions it is fairly straightforward to a. To null, we can calculate a power this equation, d is the ratio will be.! Important aspect of experimental design R_ { reduced } ^ { 2 } =0\ ) exact same cases in. Difference power 50 % of variance of college GPA a less conservative test by using larger... Illustrate how to calculate the power of different sample size calculator and as standard. For linear regression can be conducted using the function wp.anova ( ) a variable called num1 reported in first... ), which might not be possible in practice, there are no formal standards for power voltage... Effects are calculate power in r to detect in smaller samples be determined 0.573 with the rather. 0.573 with the t-distribution rather than the previous chapter of observations necessary achieve... Example. H_1$, then the probability that the power and for low voltage systems the ratio be... His prior knowledge, she expects the two variables to be correlated with a command... ( R_ { reduced } ^ { 2 } =0.5\ ) check out the help page, help power.t.test! Influences statistical power of the non-centrality parameter the number of samples for above! The definition of small, the resulting sample size, e x larger significance criterion variable. The previous chapter Simple example to illustrate how to find the powers for many tests and and.
|
{}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.