text:
# Sphere collision questions.

This topic is 4304 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Im try to implement a very simple sphere collision for particles i dont understand how to calculate the new velocity from 2 colliding objects. My maths is very limited so im having trouble understanding the very basics but i got to start some where. From nehe tutorials lesson 30 - explains how to get the new velocity off 2 colliding spheres
Quote:
 U1y and U2y are the projected vectors of the velocity vectors U1,U2 onto the axis which is perpendicular to the X_Axis. To find these vectors a few simple dot products are needed. M1, M2 is the mass of the two spheres respectively. V1,V2 are the new velocities after the impact, and V1x, V1y, V2x, V2y are the projections of the velocity vectors onto the X_Axis. In More Detail: a) Find X_Axis X_Axis = (center2 - center1); Unify X_Axis, X_Axis.unit(); b) Find Projections U1x= X_Axis * (X_Axis dot U1) U1y= U1 - U1x U2x =-X_Axis * (-X_Axis dot U2) U2y =U2 - U2x c) Find New Velocities (U1x * M1)+(U2x*M2)-(U1x-U2x)*M2 V1x= -------------------------------- M1+M2 (U1x * M1)+(U2x*M2)-(U2x-U1x)*M1 V2x= -------------------------------- M1+M2 In our application we set the M1=M2=1, so the equations get even simpler.
Dont think i follow what he means by the whole x axis thing why do i need to calculate that and wouldnt the axis change ? thx alot for any help, fishy

##### Share on other sites
I think in the example above it assumes the spheres are colliding head on
O---->           <------o     O---<-->--o     <----O o---->

##### Share on other sites

Quote:
 R is the new direction vectorI is the old direction vector before the collisionN is the Normal at the collision point The new vector R is calculated as follows: R= 2*(-I dot N)*N + I

So in theory this would just make me bounce off at a mirror angle ?

So i know at what point the sphere collides ok but how i do i calculate the normal at the collision point ?

##### Share on other sites
When it mentions N is it talking about the face normals or is this some sorta new normal that has to be calculated specifically for collision ?

Just with my particles they are all 2d billboards in 3d space.

##### Share on other sites
When the tutorial says x axis, it means the axis in the direction of the collision. For two spheres, the direction of the collision is the same as the vector from the center of one sphere to the center of the other. The code finds this direction and normalizes it to get what it is calling the x axis, which is really the collision axis. In a frictionless collision, the is the only direction in which the velocities are affected. The velocities perpendicular to this direction are unaffected.

##### Share on other sites
thx for that cleared it up slighty.

Ive implemented the way it says like so,

C = CenterPosB - CenterPosA;

VEC3 Axis;
Axis = Unit_Vec(C);

VEC3 U1, U2;
U1.x = Axis.x * (Axis.Dot_ProductVEC3(VelA));
U1.y = VelA->x - U1.x;
U2.x = -Axis.x * (-Axis.Dot_ProductVEC3(VelB));
U2.y = VelB->x - U2.x;

VelA->x = (U1.x + U2.x - (U1.x - U2.x));
VelA->y = U1.y;

The problem is that all my particles start off from a single spot so i figured they would all bounce all over the place but even with the emission rate as 2 every 10 seconds and with me only checking particle A against B as soon as they collide the velocity of A is reduced to almost zero.

Am i missing something ?

thx again.

Some of the syntax is really confusing i.e.

U1y=ArrayVel[BallColNr1]-U1x; this mean Vel.x - U1x or Vel.y - U1x or something else ><

##### Share on other sites
U1x, U1y, U2x, and U2y are all vectors. This seems to me to be a particularly confusing implementation of a collision response for two spheres...

##### Share on other sites
Sounds very simple aswell ><.

heres the link btw to that guide,
http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=30

Is there a better explination of this any where ?

##### Share on other sites
Wooo i got it to work sorry my stupidity i was calculating the unit vector wrong ><. Was doing *= mag instead of /= im still not fully sure that its working though ill have to go through the code in more detail but for now it does seem to bounce away.

One thing that im still not quite sure on though is what if the collision is in the z axis ? That method seems to only update the x and the y how would you apply this to the z aswell.

##### Share on other sites
A simpler formulation that works in any dimension goes like this:

Let the centers of the spheres be C1 and C2, and let their respective velocities be V1 and V2 and their masses be M1 and M2. e is the coefficient of restitution (0 for an inelastic collision, 1 for an elastic collision, and in between for anything else).

N = C1-C2
V = V1-V2
Impulse = -(1+e)*V*N / N*N*(1/M1 + 1/M2)
V1 = V1 + Impulse/M1
V2 = V2 + -Impulse/M2

For more information on how this is derived, you can look at the third article in Chris Hecker's series of articles on rigid body dynamics, found at http://www.d6.com/users/checker/dynamics.htm

This formulation is more concise, involves fewer operations, and works in 2 or 3 dimensions. Note that all of the quantities involved, except mass and the coefficient of restitution, are vectors.

##### Share on other sites
Wow that gives some good results :D.

Just to clarify tho N and V vectors are unit vectors ?

Nice site aswell lots of good info.

I see this sub dividing time alot so that you get the perfect position when the two spheres collide do you have to do this im just thinking cpu wise with thousands of particles ?

Mmmm for some reason i keep getting -Indo for y
Sorry for my stupidity yeah simple check to make sure N isnt equal to zero for x y z solves that problem.

In that article the guy mentions that the N and V vectors dont have to be unit vectors but for me it will only work if they are ><..

If they arnt unit vectors they collide then seem to just stay still.

[Edited by - fishleg003 on February 28, 2006 5:56:50 PM]

##### Share on other sites
N is the collision 'normal' so it must be unit length but V must not.

+y
^
|
|
|
+-------->+x

or this way:

+-------->+x
|
|
|
|
+y

??

Not sure but this can be the problem: instead of moving up, it moves down :P...if this is your problem, just negate the y impulse.

##### Share on other sites
With the equations I posted above from Chris Hecker's article, N and V do not need to be unit vectors. V in particular is definitely not a unit vector, it is the velocity of the first sphere relative to the second. N is the direction of the collision, and using the equations given it does not need to be a unit vector. Actually I made a slight mistake in the equations I wrote earlier...the updates for the velocity should be

V1 = V1 + N * Impulse/M1
V2 = V2 - N * Impulse/M2

The way I had it before didn't make sense because it was adding a scalar to a vector...the way the equations work out, N is in the numerator twice and in the denominator twice, so its magnitude cancels out. As long as N isn't zero it is fine.

The spheres can be allowed to overlap before applying the collision impulses and it will still be roughly correct. Just check that the impulse is positive before applying it. If the impulse value as calculated above is negative, that means the spheres were already moving apart, and applying it would actually cause the spheres to stick together. Which in my opinion can also look pretty neat.

##### Share on other sites
Its working but one problem i have noticed because they all start off at the same spot say 20 at once the particles go absolutely balistic bouncing all over the place since they cant get away from each other.

Not only that the velocity seems to build up really quickly its hard to explain but say it checks collision all the time as much as it can when 2 spheres are inside each other the velocity is added on a good few times before the 2 spheres seperate is that correct ?

If velocity is a unit vector it seems to be more stable ill have another play with it later.

thx alot for the help.

##### Share on other sites
You're doing something wrong...the velocity should definitely NOT be a unit vector, it should be the difference between the velocities of the spheres. Starting every sphere at the same spot is a bad idea because if they are exactly in the same spot the collision routine won't work because the difference between their centers will be the zero vector. If the calculated impulse is negative, break out early and do not change the velocities. After a single collision, the colliding spheres should be separating from each other. If the spheres are separating, the impulse calculated will be negative, so the code should break out early and not change the velocities.

##### Share on other sites

This topic is 4304 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628653
• Total Posts
2984054

• 10
• 9
• 9
• 10
• 21

format: plain


text:
• # question_answer ABC is a triangular park with AB = AC = 100 metres. A vertical tower is situated at the mid-point of BC. If the angles of elevation of the top of the tower at A and B are ${{\cot }^{-1}}\left( 3\sqrt{2} \right)$ and $\cos e{{c}^{-1}}\left( 2\sqrt{2} \right)$ respectively,  then the height of the tower (in metres) is : [JEE Main 10-4-2019 Morning] A) $10\sqrt{5}$              B) $\frac{100}{3\sqrt{3}}$C) $20$   D) $25$

$\cot \alpha =3\sqrt{2}$$\And cosec\beta =2\sqrt{2}$                     So,$\frac{x}{h}=3\sqrt{2}$                                                ...(i) And $\frac{h}{\sqrt{{{10}^{4}}-{{x}^{2}}}}=\frac{1}{\sqrt{7}}$                             ?(ii) So, from (i) & (ii) $\Rightarrow \frac{h}{\sqrt{{{10}^{4}}-18{{h}^{2}}}}=\frac{1}{\sqrt{7}}$$\Rightarrow 25{{h}^{2}}=100\times 100$ $\Rightarrow h=20.$


text:
# What products result from the reaction of hydrogen fluoride and magnesium hydroxide?

Jan 28, 2017

$\text{Magnesium fluoride and water.........}$

#### Explanation:

This is a simple acid base reaction:

$2 H F \left(a q\right) + M g {\left(O H\right)}_{2} \left(s\right) \rightarrow M g {F}_{2} \left(s\right) \downarrow + 2 {H}_{2} O \left(l\right)$

As I recall, $\text{magnesium fluoride}$ is pretty damn insoluble in aqueous solution (much more so than $M g C {l}_{2}$), so you will have to check this.

This follows the general reaction scheme:

$\text{Acid + base "rarr" salt + water}$

Which species is which in the given reaction?


text:
# Does ternary operations have associative property?

Binary Operation is a function. Right?
We know that all Binary operations have associative property.
They must be either associative or non-associative.
The condition is :
$$(a*b)*c = a*(b*c)$$ $$f(f(a, b), c) = f(a, f(b, c))$$ If this condition is true for all a, b, c combinations then the $"*"$ operation is associative.

Also we know that Unary operations does not have an associative property.
like "!" operation as a factorial of any real number.
We may say it is always associative.

• You're effectively asking for a function s.t. $f(a,b,f(c,d,e)) = f(f(a,b,c),d,e) = f(a,f(b,c,d),e)$. Some functions might satisfy this some might not. Trivial example $f(a,b,c) = a+b+c$ then it's associative. – Dan Oct 7 '13 at 8:44


text:
# Pumping lemma: Convert pumped, binary string $xy^iz$to integer

I am trying to use the pumping lemma to prove that the language consisting of the set of $0$'s and $1$'s, beginning with a $1$, such that when interpreted as an integer, that integer is prime, is not regular.

Pumping lemma is the key. If the language were regular, thered be strings $u,v,w$ such that $uv^*w\subseteq L$ and $|v|>0$ and wlog $|u|>0$, i.e. $u\in 1\{0,1\}^*$ If $U,V,W$ are the numbers represented by $u,v,w$ (where $v,w$ may have leading zeroes), then the number represented by $uv^kw$ is $U\cdot 2^{|w|+k|v|} + 2^{|w|}\cdot > \frac{2^{k|v|}-1}{2^{|v|}-1}\cdot V+W$, where $U\ge 1$. Show that these cannot all be prime.

From what I understand, you break the binary string into $U,V$ and $W$. The pumping lemma says that for a regular language, for every $i >= 0$, $UV^iW \in L$. You simply then choose an i and show that $UV^iW$ is not a member of the language.

However, I don't understand why it works that you can represent the number as $U\cdot 2^{|w|+k|v|} + 2^{|w|}\cdot \frac{2^{k|v|}-1}{2^{|v|}-1}\cdot V+W$, where $U\ge 1$


text:
# Linear oblique asymptote

1. Dec 4, 2013

### Coco12

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

what is the linear oblique asymptote of (x^5+x^3+2)/(x^4-1)
?
2. Relevant equations

x-a/p(x) = q(x) +remainder

3. The attempt at a solution

I put in all the placeholders for the divisor and the numerator and got x as the equation for the linear oblique asymptote?? Is that right??

2. Dec 4, 2013

### Mentallic

We would let

$$\frac{x^5+x^3+2}{x^4-1}\equiv \frac{(ax+b)(x^4-1)+p(x)}{x^4-1} = ax+b + \frac{p(x)}{x^4-1}$$

Where p(x) is a cubic polynomial or less (doesn't matter what it is exactly).

If we expanded (ax+b)(x4-1) then we get

$$ax^5+bx^4-ax-b$$

But we ignore the -ax-b term because that will be a part of p(x) which we've already said we don't care about. So we want the constant a to be chosen such that $ax^5=x^5$ since the coefficient of $x^5$ on the LHS must be equal to the RHS, hence a=1, and b must be chosen such that $bx^4=0$ for the same reason, hence b=0.

But we ignore the -ax-b term because that will be a part of p(x) which we've already said we don't care about.

3. Dec 4, 2013

### Coco12

Is the answer that I got correct? Thanks for taking the time to answer. I know how to do it just wondering if it's correct

File size:
2.1 KB
Views:
74
4. Dec 4, 2013

### HallsofIvy

Staff Emeritus
Yes, y= x is the "liner oblique asymptote".

5. Dec 4, 2013

### Staff: Mentor

No, this isn't correct. It's the equation of the rational function you started with.

To find the oblique asymptote, either do what Mentallic suggested or carry out the long division to get x + a proper rational function. In a proper rational function, the degree of the numerator is less than that of the denominator.

6. Dec 6, 2013

Ok thank you


text:
# Storing game settings and variables

This topic is 4985 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'll start by explaining the situation, essentially in my engine I want to have a system much like in the Quake games where you can store variables and retreive variables of either string, integer or float data types easily. I want this all to be nice and tidy in a single object with each variable having some degree of organisation, for example variables relating to system settings can be flagged as system settings and these variables might be loaded on startup, for example they maybe read in from a text based settings file, the kind of setting I'm talking about might be a variable "resolutionx" being set to the integer value 640. Also I might want game variables, for example "playername" set to a string value of "Xest" and this could be set via the console with a command such as: set playername Xest Now I have a pretty good picture of what I want in my head but the problem is how to code it, I'm an old style C programmer and have to admit I'm not totally to grips with C++ such as the limitations of templates and such. I'd like the interface to the class toring the settings to be nice and tidy, for example I could have int fnRetreiveValueAsInt(char *VariableName) and then have one for retreiving values as a string and such, but that's not what I want, I want to know if it's possible to have a single retreive value function that will work for all variable types, and whether this could lead to any potential problems, using polymorphism, could I not have: bool RetreiveValue(char *VariableName, int *VariableValue); bool RetreiveValue(char *VariableName, char *VariableValue); bool RetreiveValue(char *VariableName, float *VariableValue); Then simply return the value back to the variable passed by the pointer in the second argument depending on what type of pointer was passed, and, for error checking, use the boolean return value to declare whether the operation was a success? For example, if an int pointer is passed to retreive the value of a variable that's actually stored in the class as a char it would simply return false such that it couldn't perform a valid conversion then perform error checking on the boolean value at the function call itself for each variable lookup? As for actually storing the variables in the Settings class itself, I'm guessing I'd want a vector(Is a vector the best bet?) of templates with things like the following: string variablename; templatetype variablevalue; int variabletype; // i.e. SYSTEM_VARIABLE, GAME_VARIABLE etc. As I say I'm a little rusty with programming in general and my knowledge of C++ and templates isn't that strong, neither is my knowledge of things like RTTI (Is RTTI something that'd help me here?). Am I on the right tracks or is this system flawed in some way? Can someone recommend a better/safer/cleaner method than this? Essentially the class needs to be responsible merely for retreiving and saving variables of different types and the variables maybe added via a variety of methods - settings files at startup, game code at run time, player input via console and such. Any help, comments, ideas much appreciated, I think sorting this out will answer a lot of questions I have about templates and polymorphism, including what they can and can't do and such.

##### Share on other sites
Two words (four if you include the namespaces):
std::string. boost::variant.

Enigma

##### Share on other sites
I store all this kind of stuff in LUA scripts - its a bit of a leap but once its all working nicely its a breeze...

##### Share on other sites
If you're focusing on the Win32 platform, you might look into GetPrivateProfileString()/WritePrivateProfileString(). They are deprecated in favor of the registry, but they aren't going anywhere. These store and retrieve all data in char* strings. You can atoi() and atof() the data to ints and floats as you need them.

##### Share on other sites
Not really interested in dropping it out to scripting, it's a bit overkill for what I need. I'm not terribly keen on boost as that's not helping me solve my problem so I'll still be lacking as much of a clue as I am now and using Win32 SDK functions is out of the question as I can already do that and it doesn't give me the generic setup I'm aiming for whilst also tying me to the Win32 platform. Thanks for the advice, but was looking for something relating to my original plans I laid out and whether my theory setup is acheivable or whether it needs to be reworked completely.

##### Share on other sites
boost does help you solve the problem, and do so in a much cleaner and safer manner. Read the documentation.

Example:
#include <iostream>#include <map>#include <string>#include <sstream>#include "boost/variant.hpp"class GetInteger	:	public boost::static_visitor< int >{	public:		int operator()(int i)		{			return i;		}		int operator()(float f)		{			return f;		}		int operator()(std::string string)		{			throw std::string("Cannot convert string to int");		}};class GetString	:	public boost::static_visitor< std::string >{	public:		std::string operator()(int i)		{			std::stringstream ss;			ss << i;			return ss.str();		}		std::string operator()(float f)		{			std::stringstream ss;			ss << f;			return ss.str();		}		std::string operator()(std::string string)		{			return string;		}};std::map< std::string, boost::variant< int, float, std::string > > variables;int main(){	variables.insert(std::make_pair("resolutionx", 640));	variables.insert(std::make_pair("resolutiony", 480.0f));	variables.insert(std::make_pair("colourdepth", "32 bit"));	variables.insert(std::make_pair("playername", "Xest"));	variables.insert(std::make_pair("playerrace", 32));	try	{		std::cout << "resolutionx: " << boost::apply_visitor(GetInteger(), variables["resolutionx"]) << '\n';	}	catch (std::string & exception)	{		std::cout << "Error reading resolutionx: " << exception << '\n';	}	try	{		std::cout << "resolutiony: " << boost::apply_visitor(GetInteger(), variables["resolutiony"]) << '\n';	}	catch (std::string & exception)	{		std::cout << "Error reading resolutiony: " << exception << '\n';	}	try	{		std::cout << "colourdepth: " << boost::apply_visitor(GetInteger(), variables["colourdepth"]) << '\n';	}	catch (std::string & exception)	{		std::cout << "Error reading colourdepth: " << exception << '\n';	}	try	{		std::cout << "playername: " << boost::apply_visitor(GetString(), variables["playername"]) << '\n';	}	catch (std::string & exception)	{		std::cout << "Error reading playername: " << exception << '\n';	}	try	{		std::cout << "playerrace: " << boost::apply_visitor(GetString(), variables["playerrace"]) << '\n';	}	catch (std::string & exception)	{		std::cout << "Error reading playerrace: " << exception << '\n';	}}

Of course, you could write your visitors to disallow int to string conversions, or to parse numerical strings for string to int/float conversion etc.

Enigma

##### Share on other sites
Quote:
 Original post by Xest...and using Win32 SDK functions is out of the question as I can already do that and it doesn't give me the generic setup I'm aiming for whilst also tying me to the Win32 platform....

Fair enough. I wasn't sure if you were concerned with that or not. I'd google for things like "ini file parser", "config file parser", and "key-value file parser." Those returned a good number of hits, and you could at least get a look at some code aimed at a similar purpose.

If I were doing this, I'd probably save to a text file, and just use strings, relying on sprintf or stringstream to convert number vars to text and atoi and atof to convert back. Boost would be nicer, but it's by no means necessary. I'm not sure if I'd convert to numbers in the Get- functions, or if I'd just return a string and have the app convert based on the type of setting it's trying to fill.

##### Share on other sites
how come you dont want to do it the c-way with fnRetreiveValueAsInt?
you know just because you _can_ do something oop it doesnt have to mean you _should_ do it oop. the easiest, working, solution is often best. though sometimes its not, for example if you want to create something thats more reusable or more extendable.
now if you still want to do it the oop way, id say (as the ones before me): stl and boost is your best friends.

##### Share on other sites
This actually came up recently here, in general programming [well, not exactly, but the solution can be easily adapted to this scenario] and is far more re-usable and extensable than the C-style.

Though might not be so good to learn templating and polymorphism from.

##### Share on other sites
"boost does help you solve the problem, and do so in a much cleaner and safer manner. Read the documentation."

Yes, but it doesn't help with my understanding of what templates and such can and can't do and how to work with them properly which really doesn't help me become a better programmer for using it. Whereas I don't fancy writing my own graphics library and hence would just use OpenGL/Direct3D I feel something like this is something I should be capable of writing a home grown solution for without needing to resort to 3rd party libraries to do everything for me. This isn't so much a question of just getting it done, but more a question of understanding how to get it done. That said, I do appreciate your reply a great deal, that code snippet alone is a very nice example if I do wish to switch to boost when I've got a better understanding of C++, so thank you for that ;)

"Fair enough. I wasn't sure if you were concerned with that or not. I'd google for things like "ini file parser", "config file parser", and "key-value file parser." Those returned a good number of hits, and you could at least get a look at some code aimed at a similar purpose."

That's not so much the issue I'm struggling with, I can read and write files fine, the problem is to do with in memory storage and a generic method of accessing different variable types in memory.

"how come you dont want to do it the c-way with fnRetreiveValueAsInt?
you know just because you _can_ do something oop it doesnt have to mean you _should_ do it oop. the easiest, working, solution is often best. though sometimes its not, for example if you want to create something thats more reusable or more extendable.
now if you still want to do it the oop way, id say (as the ones before me): stl and boost is your best friends."

I'd like to try and maintain extensibility without having to modify the interface if possible, perhaps I'm being too picky here with what I want but it just seems a lot tidier to have a single function in the interface to do the job than to have to keep a function for every data type I decide to work with.

I don't mean to sound un-appreciative of the help but I'm trying to gain a specific understanding and if the reason I'm being given work arounds is because what I want to do is too difficult, flawed or some such than I'd rather be just flat out told that, if not I'd just like some kind of confirmation as to whether my solution is workable and what needs changing if anything ;) Thanks for the info so far though all ;)

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

(You must login to your GameDev.net account.)

• 13
• 9
• 15
• 14
• 46
• ### Forum Statistics

• Total Topics
634059
• Total Posts
3015296
×


text:
# Preparing Networks¶

The preparation process of the PyPSA-Eur energy system model consists of a group of snakemake rules which are briefly outlined and explained in detail in the sections below.

Not all data dependencies are shipped with the git repository. Instead we provide separate data bundles which can be obtained using the retrieve* rules (Rules retrieve*). Having downloaded the necessary data,

With these and the externally extracted ENTSO-E online map topology (data/entsoegridkit), it can build a base PyPSA network with the following rules:

Then the process continues by calculating conventional power plant capacities, potentials, and per-unit availability time series for variable renewable energy carriers and hydro power plants with the following rules:

The central rule add_electricity then ties all the different data inputs together into a detailed PyPSA network stored in networks/elec.nc.


text:
# Right triangles

Description for the calculation of right triangles and the Pythagorean theorem

## Right Triangles And Pythagorean Theorem

The Pythagorean Theorem states that in a right triangle, the square of the hypotenuse is equal to the sum of the squares of the legs. The hypotenuse is the longest side of a right triangle. It is always across from the right angle.

sed on this right triangle, you can write an equation using the Pythagorean Theorem as follows

$$a^2+b^2=c^2$$

$$\sqrt{s^2+b^2}$$

## Pythagorean triple

A Pythagorean triplet is made up of three natural numbers, which may appear as lengths of the sides of a right triangle.

• A Pythagorean triple is a right triangle whose sides are in the ratio 3:4:5

• The side lengths do not need to measure 3, 4, and 5; however, they do need to reduce to that ratio

• For example, the side lengths 9, 12, and 15 are a Pythagorean triple because it simplifies to the ratio 3:4:5

## The Converse of the Pythagorean Theorem

You can also use the Pythagorean Theorem to determine if a triangle is acute, right, or obtuse. This is known as the converse of the Pythagorean Theorem, which reads as follows

• If $$c^2 < a^2 + b^2$$, then the triangle is acute

• If $$c^2 = a^2 + b^2$$, then the triangle is right

• If $$c^2 > a^2 + b^2$$, then the triangle is obtuse

## Special Right Triangles

wo types of right triangles are considered special right triangles. One of the special right triangles has angles that measure 30°, 60°, and 90°. The other special right triangle has angles that measure 45°, 45°, and 90°. The size of the triangle does not matter; it just needs to have specific measures for its angles.

## 30°-60°-90° Triangle

The lengths of the sides of a $$30° - 60° - 90°$$ triangle are in a ratio of $$b=a·\sqrt{3}$$

The hypotenuse is twice the length of the side $$a$$ opposite the $$30°$$ angle.

• Therefore, $$a$$ must be the following $$a = c/2$$
• And $$b$$ must be $$b=c/2·\sqrt{3}$$

Using this information, you can determine the value of $$a$$ and $$b$$ for the triangle, if you know the value of $$c$$.

## 45°-45°-90° Triangle

The sides $$a$$ of a 45° - 45° - 90° triangle are the same length.

• The ratio of side lengths to hypotenuse is $$\displaystyle \frac{1}{\sqrt{2}}$$
• This results in $$\displaystyle a=\frac{c}{\sqrt{2}}$$


text:
# Coterminal & Standard Angles

We define an angle as the union of two non-collinear rays that have a common starting point. The two rays are referred to as the arms of the angle and the common starting point is called its vertex.

We can interpret an angle by rotating a ray from one position to another. When we use this interpretation of an angle, the ray to begin with is called the initial side, and the final position of ray is called the terminal side as shown in the figure.

If we rotate the ray in anti-clockwise direction, the angle formed in this way is termed as positive angle. The angle formed by clockwise rotation of ray is termed as negative angle.

## Angle in Standard Position

''An angle whose vertex lies at the origin of a rectangular coordinate system and whose initial side is directed along the positive direction of x-axis of that coordinate system is said to be in standard position.''

Angles shown in the figures below are in standard position.

## Coterminal Angles

''Angles having the same initial and terminal sides are called coterminal angles.''

Let there be an angle \angleAOB with OA as the initial side and OB as the terminal side as shown in the figures below:

Note that all the three angles \angleAOB in the above figures have the same initial and terminal sides. Hence these are coterminal angles.

That is (\theta+2\pi), (\theta+4\pi) and in general \theta+2(k)\pi are all coterminal angles with \theta where k is an integer.

Note: If \theta is an angle measured in degrees, then \theta \pm k(360^\circ) , where k is an integer, is an angle coterminal with \theta.

If \theta is measured in radians, then \theta \pm 2(k)\pi is an angle coterminal with \theta.

##### Example 1:

Locate the following angles in standard position on a rectangular coordinate system.

1. 135^\circ
2. -640^\circ
3. 310^\circ

##### Example 2:

Find two +ve and two -ve angles that are coterminal with 60^\circ.

Solution: We are given that \theta = 60^\circ

Two positive angles coterminal with \theta = 60^\circ are:

\theta + 360^\circ = 60^\circ + 360^\circ = 420^\circ and \theta + 2(360^\circ) = 60^\circ + 720^\circ = 780^\circ

Two negative angles coterminal with \theta = 60^\circ are:

\theta - 360^\circ = 60^\circ - 360^\circ = - 300^\circ and \theta - 2(360^\circ) = 60^\circ - 720^\circ = -660^\circ

##### Example 3:

Find one positive and one negative angle coterminal with (2\pi)/3

Solution: One positive angle coterminal with (2\pi)/3 is:

( 2\pi)/3 + 2\pi = (2\pi+6\pi)/3 = (8\pi)/3

One negative angle coterminal with (2\pi)/3 is:

( 2\pi)/3- 2\pi = (2\pi - 6\pi)/3 = ( - 4\pi)/3

#### Become a member today!

Register (it’s Free)


text:
# 'S No Problem

The Yllihc Engineering and Technological Institute (YETI), located in northern Snowblovia, has two problems: snow and money. Specifically, they have too much of the former and not enough of the latter. Every winter (and fall and spring, for that matter) the campus is covered with blankets of snow, and the sidewalks connecting campus buildings become impassable. To continue functioning, YETI needs to clear the snow from the sidewalks connecting the buildings of the campus. Since budget is an issue, these sidewalks are a minimal set that allow a path to exist between any two buildings.

With the money saved by not building more sidewalks, YETI bought two snow blowers. To clear the snow with them, two staff members take the two snow blowers out of the buildings (or building) they are stored in, and push them along the sidewalks, clearing the snow. Each sidewalk must be traversed at least once. Each snow blower, after it has finished, is stored in the building it is currently next to (and, during the next snowfall, the snow blowers will be pushed in the reverse direction—and so on, throughout the eleven months of the snow season).

The YETI maintenance crew want to choose the storage buildings of the snow blowers and design the routes along which they will be pushed, so that they minimize the total distance the two machines will travel out in the cold (to protect both the precious equipment and the staff members from freezing). Note that the routes might involve pushing along already-cleared sidewalks, as seen in Figure 1, which shows an optimal solution for the sidewalk layout of Sample Input 1.

YETI would ask their Computer Science Department to figure this out, but it was wiped out in the Great Blizzard of ’$06$, so they have come to you for help.

## Input

The first line of input contains an integer $n$ ($4\leq n\leq 100\, 000$), the number of buildings on the YETI campus. Buildings are numbered from $1$ to $n$. Each of the remaining $n-1$ lines contains three integers $a$, $b$, and $d$ indicating that a sidewalk exists between buildings $a$ and $b$ ($1 \leq a, b \leq n$; $a\ne b$) of length $d$ ($1\leq d\leq 500$).

## Output

Output the minimum total distance the snow blowers must travel to remove snow from all sidewalks.

Sample Input 1 Sample Output 1
7
1 4 2
2 4 3
3 4 1
4 5 1
5 6 2
5 7 4

15

Sample Input 2 Sample Output 2
4
1 2 1
2 3 2
3 4 3

6


text:
## C Specification

Data can be retrieved from a validation cache object using the command:

// Provided by VK_EXT_validation_cache
VkResult vkGetValidationCacheDataEXT(
VkDevice                                    device,
VkValidationCacheEXT                        validationCache,
size_t*                                     pDataSize,
void*                                       pData);

## Parameters

• device is the logical device that owns the validation cache.

• validationCache is the validation cache to retrieve data from.

• pDataSize is a pointer to a value related to the amount of data in the validation cache, as described below.

• pData is either NULL or a pointer to a buffer.

## Description

If pData is NULL, then the maximum size of the data that can be retrieved from the validation cache, in bytes, is returned in pDataSize. Otherwise, pDataSize must point to a variable set by the user to the size of the buffer, in bytes, pointed to by pData, and on return the variable is overwritten with the amount of data actually written to pData. If pDataSize is less than the maximum size that can be retrieved by the validation cache, at most pDataSize bytes will be written to pData, and vkGetValidationCacheDataEXT will return VK_INCOMPLETE instead of VK_SUCCESS, to indicate that not all of the validation cache was returned.

Any data written to pData is valid and can be provided as the pInitialData member of the VkValidationCacheCreateInfoEXT structure passed to vkCreateValidationCacheEXT.

Two calls to vkGetValidationCacheDataEXT with the same parameters must retrieve the same data unless a command that modifies the contents of the cache is called between them.

Applications can store the data retrieved from the validation cache, and use these data, possibly in a future run of the application, to populate new validation cache objects. The results of validation, however, may depend on the vendor ID, device ID, driver version, and other details of the device. To enable applications to detect when previously retrieved data is incompatible with the device, the initial bytes written to pData must be a header consisting of the following members:

Table 1. Layout for validation cache header version VK_VALIDATION_CACHE_HEADER_VERSION_ONE_EXT
Offset Size Meaning

0

4

length in bytes of the entire validation cache header written as a stream of bytes, with the least significant byte first

4

4

a VkValidationCacheHeaderVersionEXT value written as a stream of bytes, with the least significant byte first

8

VK_UUID_SIZE

a layer commit ID expressed as a UUID, which uniquely identifies the version of the validation layers used to generate these validation results

The first four bytes encode the length of the entire validation cache header, in bytes. This value includes all fields in the header including the validation cache version field and the size of the length field.

The next four bytes encode the validation cache version, as described for VkValidationCacheHeaderVersionEXT. A consumer of the validation cache should use the cache version to interpret the remainder of the cache header.

If pDataSize is less than what is necessary to store this header, nothing will be written to pData and zero will be written to pDataSize.

Valid Usage (Implicit)
• VUID-vkGetValidationCacheDataEXT-device-parameter
device must be a valid VkDevice handle

• VUID-vkGetValidationCacheDataEXT-validationCache-parameter
validationCache must be a valid VkValidationCacheEXT handle

• VUID-vkGetValidationCacheDataEXT-pDataSize-parameter
pDataSize must be a valid pointer to a size_t value

• VUID-vkGetValidationCacheDataEXT-pData-parameter
If the value referenced by pDataSize is not 0, and pData is not NULL, pData must be a valid pointer to an array of pDataSize bytes

• VUID-vkGetValidationCacheDataEXT-validationCache-parent
validationCache must have been created, allocated, or retrieved from device

Return Codes
On success, this command returns
• VK_SUCCESS

• VK_INCOMPLETE

On failure, this command returns
• VK_ERROR_OUT_OF_HOST_MEMORY

• VK_ERROR_OUT_OF_DEVICE_MEMORY

## Document Notes

For more information, see the Vulkan Specification

This page is extracted from the Vulkan Specification. Fixes and changes should be made to the Specification, not directly.

Copyright 2014-2022 The Khronos Group Inc.

SPDX-License-Identifier: CC-BY-4.0


text:
# Hull White help needed

I've been trying to calibrate Hull-White 1 Factor & 2 Factor model using Caps but I've some major doubts about my methodology, and would really appreciate some help.

I am using these formulas

For getting the instantaneous forward rates needed in theta formula i used the central difference method for getting the derivatives at the discrete time intervals t

(from excel data.....assumed P(t,T)= math.exp(r*t))

1) In the A formula for P(t,T) which formula should we use? e^-rt or the Ae^-B*r(t)...If I have to use the latter one, what should I take r? the same r value i used initially for calculating DFs? or the r(t) analytical formula after the Hull White calibration? (I calibrated a,sigma value using sum squared min error with implied caplet values from formula given above and market values that i had)

2) After the calibration step, how do i get the r(t) values? i have to use monte carlo simulation

Thank you once again for your time, I am completely new to this field & would appreciate a helping hand. or the

On the formula of the zero bond: The representation of the zero bond with r involves an integral and even worse, an expectation ($$P(t,T) = E( exp(-\int_t^T r(\tau) d\tau )$$). The core advantage of the HW Model is that you have an analytic formula for P in terms of A and B. So you would use that formula. Note that the paper mentioned above also gives the correct values for A and B under the simulation scheme. Its an advantage to have the correct analytic formula under the simulated model instead of using the formula derived from the continuous time SDE, but being in a discretised setup.


text:
1. anonymous

Set u=arctan(x), so that du= 1/(1+x^2). Thus, using this u-substitution, the integral is equivalent to the integral of sin(u). Since the integral of sin(u) is -cos(u)+C, the final answer is just $\sin (\tan^{-1} (x))+C$ Note also that sin(arctan(x)) is the same as $x/\sqrt{x^2+1}$ So that function plus your constant of integration is also a correct solution.

2. anonymous

Sorry, it should be $-\cos (\tan^{-1} (x))+C$

3. anonymous

thanx

4. anonymous

Also, that means that the alternate answer is instead $1/\sqrt{x^2+1} + C$


text:
# Finding a stock traded at two venues

For a project of mine I need to find a stock that is traded on two venues, e.g. NYSE and NASDAQ, but could be others.

So I need to use data from both venues.

Does anyone know how one would go about finding a stock that are traded on two venues?

Because it seems like an overly tedious task to go through the single stocks one by one and check if they are on another exchange. Are there e.g. a list somewhere with this information?

Another information that is important in my choice is, that it needs to have a very large average trade volume.


text:
Unbounded complexes, resolutions and computation of derived functors - MathOverflow most recent 30 from http://mathoverflow.net 2013-06-20T03:13:51Z http://mathoverflow.net/feeds/question/107405 http://www.creativecommons.org/licenses/by-nc/2.5/rdf http://mathoverflow.net/questions/107405/unbounded-complexes-resolutions-and-computation-of-derived-functors Unbounded complexes, resolutions and computation of derived functors Mario Carrasco 2012-09-17T17:38:07Z 2012-09-17T23:06:19Z
Hey guys, let $F: \mathcal{A} \rightarrow \mathcal{B}$ be a left exact functor between abelian categories with enough injectives, let $K \in Kom(\mathcal{A})$ be an unbounded complex, I've heard that you can construct resolutions and define a derived functor $RF$ for $K$ but I was wondering:

1 - Are the resolutions similar to Cartan-Eilenberg resolutions for bounded complexes, where you find an injective (projective) resolution for each member $K^i$ of $K$ and check it satisfies certain properties?

2 - Can you define filtrations, and a spectral sequence to compute the derived functors?

Any good references on this?
 http://mathoverflow.net/questions/107405/unbounded-complexes-resolutions-and-computation-of-derived-functors/107421#107421 Answer by Ralph for Unbounded complexes, resolutions and computation of derived functors Ralph 2012-09-17T21:00:05Z 2012-09-17T23:06:19Z
All references below (unless otherwise stated) refer to Weibel (We): An Introduction to Hom. Algebra. Futhermore I consider projective resolutions and assume $\mathcal{A}$ has enough projectives and $F$ is right exact since this case is treated in Weibel. The case of injective resolutions can be easily adapted by switching to the opposite category [We, 2.3.4].

Let $Ch(\mathcal{A})$ be the category of (unbounded) chain complexes in $\mathcal{A}$. Since $\mathcal{A}$ is abelian, $Ch(\mathcal{A})$ is abelian as well [We, Th. 1.2.3] and has enough projectives [We, 2.2.2]. The functor $F: \mathcal{A} \to \mathcal{B}$ induces a functor $Ch(F): Ch(\mathcal{A}) \to Ch(\mathcal{B})$. A morphism $h: C \to D$ of chain complees in $\mathcal{A}$ is epi, iff each $h_i:C_i \to D_i$ is epi [We, Proof of 1.2.3]. Hence, the right exactness of $F$ implies that $Ch(F)$ is also right exact.

In summary, we have shown: $Ch(F)$ is a right exact functor between abelian categories and $Ch(\mathcal{A})$ has enough projectives. Consequently, $Ch(F)$ has a left derived functor and everything what can be done for $L_\ast F$ (i.e. filtations, spectral sequences, etc.) can also be done for $L_\ast Ch(F)$.

A discussion of projective resolutions in $Ch(\mathcal{A})$ can be found in my answer to this question:

http://mathoverflow.net/questions/103584/on-the-difference-between-a-projective-chain-complex-and-a-level-wise-projective/103591#103591

Similar, a chain complex $I$ in $\mathcal{A}$ (which is now supposed to have enough injectives) is an injective object in $Ch(\mathcal{A})$, iff $I$ consists of injective objects $I_i\in \mathcal{A}$ such that all short sequences $$0 \to \ker(d_i) \to I_i \to \operatorname{im}(d_i) \to 0$$ are exact and do split.


text:
# The metafor Package

A Meta-Analysis Package for R

### Sidebar

tips:weights_in_rma.mv_models

## Weights in Models Fitted with the rma.mv() Function

One of the fundamental concepts underlying a meta-analysis is the idea of weighting: More precise estimates are given more weight in the analysis then less precise estimates. In 'standard' fixed- and random-effects models (such as those that can be fitted with the rma() function), the weighting scheme is quite simple and covered in standard textbooks on meta-analysis. However, in more complex models (such as those that can be fitted with the rma.mv() function), the way estimates are weighted is more complex. Here, I will discuss some of those intricacies.

### Models Fitted with the rma() Function

To start, let's discuss the standard models first. Here, we are meta-analyzing a set of independent estimates and so we can use the rma() function. For illustration purposes, I will use (once again) the BCG vaccine dataset. We start by computing the log risk ratios and corresponding sampling variances for the 13 trials included in this dataset.

library(metafor)
dat <- dat.bcg
dat <- escalc(measure="RR", ai=tpos, bi=tneg, ci=cpos, di=cneg, data=dat,
slab=paste0(dat$author, ", ", dat$year))
dat
   trial               author year tpos  tneg cpos  cneg ablat      alloc      yi     vi
1      1              Aronson 1948    4   119   11   128    44     random -0.8893 0.3256
2      2     Ferguson & Simes 1949    6   300   29   274    55     random -1.5854 0.1946
3      3      Rosenthal et al 1960    3   228   11   209    42     random -1.3481 0.4154
4      4    Hart & Sutherland 1977   62 13536  248 12619    52     random -1.4416 0.0200
5      5 Frimodt-Moller et al 1973   33  5036   47  5761    13  alternate -0.2175 0.0512
6      6      Stein & Aronson 1953  180  1361  372  1079    44  alternate -0.7861 0.0069
7      7     Vandiviere et al 1973    8  2537   10   619    19     random -1.6209 0.2230
8      8           TPT Madras 1980  505 87886  499 87892    13     random  0.0120 0.0040
9      9     Coetzee & Berjak 1968   29  7470   45  7232    27     random -0.4694 0.0564
10    10      Rosenthal et al 1961   17  1699   65  1600    42 systematic -1.3713 0.0730
11    11       Comstock et al 1974  186 50448  141 27197    18 systematic -0.3394 0.0124
12    12   Comstock & Webster 1969    5  2493    3  2338    33 systematic  0.4459 0.5325
13    13       Comstock et al 1976   27 16886   29 17825    33 systematic -0.0173 0.0714

Variable yi contains the log risk ratios and variable vi the corresponding sampling variances.

We now fit fixed- and random-effects models to these estimates.

res.fe <- rma(yi, vi, data=dat, method="FE")
res.re <- rma(yi, vi, data=dat)

Next, we extract the weights assigned to the estimates in these two models with the weights() function (the values are given in percent) and assemble these values in a matrix with two columns.

w.fe.re <- cbind(
paste0(formatC(weights(res.fe), format="f", digits=1, width=4), "%"),
paste0(formatC(weights(res.re), format="f", digits=1, width=4), "%"))

Finally, we create a forest plot of the estimates. We add a bit of space at the bottom (by adjusting ylim), add the summary estimates from the two models to the bottom (with the addpoly() function), and also add the weight information from the matrix above as additional elements to the plot (via the ilab and ilab.xpos arguments). Some extra column labels are added with text() and the segments() function is used to add the line under the 'Weights' column label.

forest(dat$yi, dat$vi, xlim=c(-11,5), ylim=c(-2.5, 16), header=TRUE, atransf=exp,
at=log(c(1/16, 1/4, 1, 4, 8)), digits=c(2L,4L), ilab=w.fe.re, ilab.xpos=c(-6,-4))
abline(h=0)
text(-6, 15, "FE Model", font=2)
text(-4, 15, "RE Model", font=2)
text(-5, 16, "Weights", font=2)
segments(-7, 15.5, -3, 15.5)

In the FE model, the weights given to the estimates are equal to $w_i = 1 / v_i$, where $v_i$ is the sampling variance of the $i$th study. This is called 'inverse-variance weighting' and can be shown to be the most efficient way of weighting the estimates (i.e., the summary estimate has the lowest possible variance and is therefore most precise). As a result, the estimates with the lowest sampling variances, namely the ones from Stein and Aronson (1953), TPT Madras (1980), and Comstock et al (1974) are given considerably more weight than the rest of the studies.1) Together, these three studies receive almost 80% of the total weight and therefore exert a great deal of influence on the summary estimate. Especially the TPT Madras study 'pulls' the estimate to the right (closer to a risk ratio of 1).

In the RE model, the estimates are weighted with $w_i = 1 / (\hat{\tau}^2 + v_i)$. Therefore, not only the sampling variance, but also the (estimated) amount of heterogeneity (i.e., the variance in the underlying true effects) is taken into consideration when determining the weights. When $\hat{\tau}^2$ is large (relative to the size of the sampling variances), then the weights actually become quite similar to each other. Hence, smaller (less precise) studies may receive almost as much as weight as larger (more precise) studies. We can in fact see this happening in the present example. While the three studies mentioned above still receive the largest weights, their weights are now much more similar to those of the other studies. As a result, the summary estimate is not as strongly pulled to the right by the TPT Madras study.

The weights used in fixed- and random-effects models are the inverse of the model-implied variances of the observed outcomes. For example, in the RE model, the model considers two sources of variability that affect the observed outcomes: sampling variability ($v_i$) and heterogeneity ($\hat{\tau}^2$). The sum of these two sources of variability is $\hat{\tau}^2 + v_i$ and the weights are therefore $w_i = 1 / (\hat{\tau}^2 + v_i)$. The summary estimate is then simply the weighted average of the estimates, namely $$\hat{\mu} = \frac{\sum_{i=1}^k w_i y_i}{\sum_{i=1}^k w_i}.$$ By comparing

wi <- 1 / (res.re$tau2 + dat$vi)
sum(wi * dat$yi) / sum(wi) [1] -0.7145323 with the summary estimate from the random-effects model, namely coef(res.re) [1] -0.7145323 we can see that this is correct. ### Models Fitted with the rma.mv() Function Models fitted with the rma.mv() will typically be more complex than those fitted with rma().2) In particular, they will usually involve multiple random effects and possibly correlated sampling errors. See Konstantopoulos (2011) and Berkey et al. (1998) for two illustrative examples. I will use the former example to discuss how the weighting works in such models. The example involves studies that were conducted at schools that in turn were nested within a higher-ordering grouping variable (districts). This leads to a multilevel structure that we want to account for in the analysis. First, let's copy the data into dat (just to save some typing down the road) and examine the first 8 rows of the dataset. We see that there are 4 studies in the first and second district each. dat <- dat.konstantopoulos2011 head(dat, 8)  district school study year yi vi 1 11 1 1 1976 -0.180 0.118 2 11 2 2 1976 -0.220 0.118 3 11 3 3 1976 0.230 0.144 4 11 4 4 1976 -0.300 0.144 5 12 1 5 1989 0.130 0.014 6 12 2 6 1989 -0.260 0.014 7 12 3 7 1989 0.190 0.015 8 12 4 8 1989 0.320 0.024 Variable yi contains the standardized mean differences and vi the corresponding sampling variances. To analyze these data, we use a multilevel model with random effects for districts and schools within districts. res <- rma.mv(yi, vi, random = ~ 1 | district/school, data=dat) res Multivariate Meta-Analysis Model (k = 56; method: REML) Variance Components: estim sqrt nlvls fixed factor sigma^2.1 0.0651 0.2551 11 no district sigma^2.2 0.0327 0.1809 56 no district/school Test for Heterogeneity: Q(df = 55) = 578.8640, p-val < .0001 Model Results: estimate se zval pval ci.lb ci.ub 0.1847 0.0846 2.1845 0.0289 0.0190 0.3504 * --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 The model now considers three sources of variability: Between-district heterogeneity ($\hat{\sigma}^2_1$), within-district heterogeneity ($\hat{\sigma}^2_2$), and sampling variability ($v_i$). The model-implied variances of the estimates are then the sum of these three sources of variability (i.e.,$\hat{\sigma}^2_1 + \hat{\sigma}^2_2 + v_i$). However, the summary estimate from the model in not simply the weighted average of the estimates with weights given by$w_i = 1 / (\hat{\sigma}^2_1 + \hat{\sigma}^2_2 + v_i)$. This weighted average is: wi <- 1 / (sum(res$sigma2) + dat$vi) sum(wi * dat$yi) / sum(wi)
[1] 0.127597

But this is not equal to the summary estimate computed by rma.mv():

coef(res)
[1] 0.1847132

The two values are not the same, because the model also implies a certain amount of covariance between the effects, which is also taken into consideration when computing the summary estimate. We can examine the model implied marginal variance-covariance (var-cov) matrix of the estimates (or here, the first 8 rows and columns) with:

round(vcov(res, type="obs")[1:8,1:8], 3)
      1     2     3     4     5     6     7     8
1 0.216 0.065 0.065 0.065 0.000 0.000 0.000 0.000
2 0.065 0.216 0.065 0.065 0.000 0.000 0.000 0.000
3 0.065 0.065 0.242 0.065 0.000 0.000 0.000 0.000
4 0.065 0.065 0.065 0.242 0.000 0.000 0.000 0.000
5 0.000 0.000 0.000 0.000 0.112 0.065 0.065 0.065
6 0.000 0.000 0.000 0.000 0.065 0.112 0.065 0.065
7 0.000 0.000 0.000 0.000 0.065 0.065 0.113 0.065
8 0.000 0.000 0.000 0.000 0.065 0.065 0.065 0.122

The diagonal elements of this matrix are indeed equal to $\hat{\sigma}^2_1 + \hat{\sigma}^2_2 + v_i$:

round(sum(res$sigma2) + dat$vi[1:8], 3)
[1] 0.216 0.216 0.242 0.242 0.112 0.112 0.113 0.122

But there are also non-zero off-diagonal elements. In particular, note how the first two districts (with 4 estimates each) result in $4 \times 4$ blocks in this matrix. The off-diagonal elements in these blocks are covariances, which are equal to $\hat{\sigma}^2_1$ (i.e., the estimated between-district variance component) in this type of model. Hence, the first 6 rows and columns of the var-cov matrix are equal to $$M = \begin{bmatrix} \hat{\sigma}^2_1 + \hat{\sigma}^2_2 + v_1 & \hat{\sigma}^2_1 & \hat{\sigma}^2_1 & \hat{\sigma}^2_1 & & \\ \hat{\sigma}^2_1 & \hat{\sigma}^2_1 + \hat{\sigma}^2_2 + v_2 & \hat{\sigma}^2_1 & \hat{\sigma}^2_1 & & \\ \hat{\sigma}^2_1 & \hat{\sigma}^2_1 & \hat{\sigma}^2_1 + \hat{\sigma}^2_2 + v_3 & \hat{\sigma}^2_1 & & \\ \hat{\sigma}^2_1 & \hat{\sigma}^2_1 & \hat{\sigma}^2_1 & \hat{\sigma}^2_1 + \hat{\sigma}^2_2 + v_4 & & \\ & & & & \hat{\sigma}^2_1 + \hat{\sigma}^2_2 + v_5 & \hat{\sigma}^2_1 \\ & & & & \hat{\sigma}^2_1 & \hat{\sigma}^2_1 + \hat{\sigma}^2_2 + v_6 \\ \end{bmatrix}.$$ As in the documentation of the rma.mv() function (see help(rma.mv)), this matrix is referred to as $M$ (for the Marginal var-cov matrix of the estimates implied by the model).

To compute the summary estimate, we need to take the inverse of this matrix. As a result, we not only have weights, but actually an entire weight matrix. We can inspect this matrix (or the first 8 rows and columns) with:

round(weights(res, type="matrix")[1:8,1:8], 3)
       1      2      3      4      5      6      7      8
1  5.533 -1.102 -0.939 -0.939  0.000  0.000  0.000  0.000
2 -1.102  5.533 -0.939 -0.939  0.000  0.000  0.000  0.000
3 -0.939 -0.939  4.857 -0.801  0.000  0.000  0.000  0.000
4 -0.939 -0.939 -0.801  4.857  0.000  0.000  0.000  0.000
5  0.000  0.000  0.000  0.000 16.664 -4.733 -4.633 -3.898
6  0.000  0.000  0.000  0.000 -4.733 16.664 -4.633 -3.898
7  0.000  0.000  0.000  0.000 -4.633 -4.633 16.412 -3.817
8  0.000  0.000  0.000  0.000 -3.898 -3.898 -3.817 14.414

Since the var-cov matrix is 'block-diagonal', each block in the weight matrix is actually the inverse of the corresponding block from the $M$ matrix (you can check this for example for the first district with round(solve(vcov(res, type="obs")[1:4,1:4]), 3)).

Let $W = M^{-1}$ denote the weight matrix. Also, let $X$ denote the model matrix, which contains the values of the variables corresponding to the fixed effects. In the present case, the model just contains an intercept term and no further predictors/moderators and hence the model matrix is a single column of 1s (which can be extracted with model.matrix(res)). Finally, let $y$ denote the (column) vector with the estimates. Then the fixed effects are estimated with $$b = (X'WX)^{-1} X'Wy.$$ This is a so-called generalized least squares (GLS) estimator. For the present model, this yields a single number, namely the estimated intercept (i.e., the pooled/summary estimate). We can check that this works by manually crunching through the matrix algebra.3)

W <- weights(res, type="matrix")
X <- model.matrix(res)
y <- cbind(dat$yi) solve(t(X) %*% W %*% X) %*% t(X) %*% W %*% y [1] 0.1847132 This is indeed the same value as we obtained above with coef(res). For those less familiar with matrix algebra, the equation that provides the summary estimate for such an 'intercept-only model' can also be written in the more familiar summation notation. Let$w_{ij}$denote the element in the$i$th row and$j$th column of the weight matrix and let$y_i$denote the$i$th estimate (with$i = 1, \ldots, k$). Then $$\hat{\mu} = \frac{\sum_{i=1}^k (\sum_{j=1}^k w_{ij}) y_i}{\sum_{i=1}^k \sum_{j=1}^k w_{ij}}.$$ The denominator of this fraction is just the sum of all elements in the weight matrix. In the numerator, we sum up the weights in each column of the weight matrix (which is the same as taking the sum in each row, since the weight matrix is symmetric) and multiply this sum by the corresponding estimate. This is done for each estimate and the resulting values are summed up. Let's check again that this is correct: W <- weights(res, type="matrix") sum(rowSums(W) * dat$yi) / sum(W)
[1] 0.1847132

While rowSums(W) takes the sum of all weight values in each row, most of those values are actually zeros. Hence, for each estimate, we really just need to sum up the values that are part of the block to which an estimate belongs. For example, for the first estimate (i.e., dat$yi[1]), we just need to sum up the first four values in the first row, that is, we would sum up: W[1,1:4]  1 2 3 4 5.5325581 -1.1015344 -0.9394859 -0.9394859 For the second estimate, we would sum up W[2,1:4]. For the fifth estimate (which belongs to the second district), we would sum up W[5,5:8]. And so on. If we look at the equation above again, we should note that$\hat{\mu}$is actually still a weighted average of the estimates, but now the weight given to the$i$th estimate is equal to$\sum_{j=1}^k w_{ij}$. These 'row-sum weights' can be obtained with: weights(res, type="rowsum")[1:8]  1 2 3 4 5 6 7 8 1.824641 1.824641 1.556215 1.556215 2.430599 2.430599 2.379682 2.002198 They are given as percentages. We can use these weights to compute the weighted average of the estimates, which again yields the summary estimate: wi <- weights(res, type="rowsum") sum(wi * dat$yi) / sum(wi)
[1] 0.1847132

By examining the weight matrix, we can also build some intuition how the model accounts for multiple estimates coming from the same district. Note that the off-diagonal elements in the blocks of the weight matrix are negative. This results in a certain amount of downweighting of the estimates, so that districts contributing many estimates do not automatically receive tons of weight when computing the summary estimate. To illustrate this, we can compute the sum of the row-sum weights within each district. In addition, the table below shows how many estimates each district contributes.

data.frame(k = c(table(dat$district)), weight = sapply(split(wi, dat$district), sum))
     k    weight
11   4  6.761714
12   4  9.243078
18   3  8.536540
27   4  9.506693
56   4  9.502062
58  11 10.328499
71   3  8.943803
86   8 10.320158
91   6  9.883123
108  5  9.203041
644  4  7.771289

While district 58, which contributes 11 estimates, does receive the most weight, this is closely followed by district 86, which contributes 8 estimates. And not much further behind are districts 27 and 56, which 'only' contribute 4 estimates. This should alleviate, at least to some extent, worries that districts contributing many estimates are receiving 'too much weight' in the analysis.

Note that the degree of downweighting depends on the covariance between the estimates, which in the present model is simply the between-district heterogeneity. This variance component is quite large in the illustrative example (almost twice as large as the within-district heterogeneity; see res$sigma2[1] / res$sigma2[2]). In cases where this ratio is much smaller, clusters contributing many estimates will receive proportionally more weight (although the sampling variances also play a role here, so many imprecise estimates may still not receive much weight after all).

### Conclusions

The example above shows that the weighting scheme underlying more complex models (that can be fitted with the rma.mv() function) is not as simple as in the 'standard' fixed- and random-effects models (that can be fitted with the rma() function). Depending on the random effects included in the model (and the var-cov matrix of the sampling errors), the model may imply a certain degree of covariance between the estimates, which needs to be taken into consideration when estimating the fixed effects (e.g., the pooled/summary estimate) and their corresponding standard errors.

Note: James Pustejovsky has written up a very nice blog post which goes even deeper into this topic.

### References

Berkey, C. S., Hoaglin, D. C., Antczak-Bouckoms, A., Mosteller, F., & Colditz, G. A. (1998). Meta-analysis of multiple outcomes by regression with random effects. Statistics in Medicine, 17(22), 2537–2550.

Konstantopoulos, S. (2011). Fixed effects and variance components estimation in three-level meta-analysis. Research Synthesis Methods, 2(1), 61–76.

1)
Depending on the outcome measure, the sampling variance of an estimate is not just an inverse function of the sample size of the study, but can also depend on other factors (e.g., for log risk ratios as used in the present example, the prevalence of the outcome also matters). Therefore, while Stein and Aronson (1953) has a smaller sample size than for example Hart and Sutherland (1977), it has a smaller sampling variance and hence receives more weight. However, roughly speaking, the weight an estimate receives is directly related to the study's sample size.
2)
But see here for a discussion of how rma.mv() can be used to fit the same models that can be fitted with rma().
3)
In general, it is not a good idea to compute the fixed effects in this way, because the matrix inversion is numerically unstable. The rma.mv() function therefore uses a Cholesky decomposition for obtaining the estimates of the fixed effects.


text:
# calculate $\int_0^{\pi}\frac {x}{1+\cos^2x}dx$

Same to the tag

calculate $\int_0^{\pi}\frac {x}{1+\cos^2x}dx$.

Have no ideas on that.

Any suggestion?

Many thanks

Using $\int_a^bf(x)\ dx=\int_a^bf(a+b-x)\ dx$

$$I=\int_0^\pi\dfrac x{1+\cos^2x}dx=\int_0^\pi\dfrac{\pi-x}{1+\cos^2(\pi-x)}dx$$

$$I+I=\pi\int_0^\pi\dfrac1{1+\cos^2x}dx$$

$$\int_0^\pi\dfrac1{1+\cos^2x}dx=\int_0^\pi\dfrac{\sec^2x}{2+\tan^2x}dx$$

Set $\tan x=u$

• Hi, thank you very much. I am wondering that how you come with the idea $\int_a^b f(x) dx = \int_a^bf(a+b-x) dx$ – Chenxiao XU Jan 21 '16 at 16:27
• @Lab How does that substitution work for pi/2? – imranfat Jan 21 '16 at 16:28
• @imranfat, Try and let me know:) – lab bhattacharjee Jan 21 '16 at 16:31
• @labbhattacharjee Of course, the given integral is integrable over 0 to pi, but not anymore with the u-sub. One should then split the integral at pi/2 so that you get an answer that involves arctan(inf) that ofcourse leads to an answer in terms of pi. I thought that would be useful info for the OP – imranfat Jan 21 '16 at 16:33

Or...along the same lines

\begin{align}\int_0^{\pi} \frac{x^2}{1+\cos^2{x}} &= \int_0^{\pi} \frac{(\pi-x)^2}{1+\cos^2{x}}\\ &= \pi^2 \int_0^{\pi} \frac{1}{1+\cos^2{x}} - 2 \pi \int_0^{\pi} \frac{x}{1+\cos^2{x}} + \int_0^{\pi} \frac{x^2}{1+\cos^2{x}} \end{align}

Thus,

$$\int_0^{\pi} \frac{x}{1+\cos^2{x}} = \frac{\pi}{2} \int_0^{\pi} dx \frac{1}{1+\cos^2{x}}$$

..and use the sub $x = \arctan{u}$, etc.

ALTERNATIVE COMPLEX SOLUTION

We can use an integration over the unit circle, in the spirit of a similar problem I have done before. To start, consider

\begin{align}\int_0^{2 \pi} dx \frac{x}{1+\cos^2{x}} &= \int_0^{\pi} dx \frac{x}{1+\cos^2{x}} + \int_{\pi}^{2 \pi} dx \frac{x}{1+\cos^2{x}}\\ &= 2 \int_0^{\pi} dx \frac{x}{1+\cos^2{x}} + \pi \int_0^{\pi} dx \frac{1}{1+\cos^2{x}} + \end{align}

So we can get the integral we want in terms of an integral over a unit circle. (Yes, and also in terms of the integral above...but at this point we're just having fun and exploring, not being efficient.)

Now, consider

$$J(a) = \int_0^{2 \pi} dx \frac{e^{i a x}}{1+\cos^2{x}}$$

Then

$$\int_0^{2 \pi} dx \frac{x}{1+\cos^2{x}} = -i J'(0)$$

Now, let's consider

$$-i \oint_C \frac{dz}{z} \frac{z^a}{1+\frac14 (z+z^{-1})^2} = -i 4 \oint_C dz \frac{z^{a+1}}{z^4+6 z^2+1}$$

where $C$ is a keyhole contour about $(0,1]$ and around the unit circle. The only poles inside the unit circle are at $z_{\pm} = \pm i (\sqrt{2}-1)$. Thus, by the residue theorem, we may write the contour integral as

$$J(a) - i 4 (1- e^{i 2 \pi a}) \int_0^1 dx \frac{x^{a+1}}{x^4+6 x^2+1} = i 2 \pi (-i 4) \frac{(\sqrt{2}-1)^{a+1} \left (e^{i \pi/2 (a+1)} - e^{i 3 \pi/2 (a+1)} \right )}{4 i (\sqrt{2}-1)[-(\sqrt{2}-1)^2+3] }$$

Note that the arguments of the poles are $\pi/2$ and $3 \pi/2$ in keeping with the definition of the contour $C$. Thus,

$$J(a) = i 4 (1- e^{i 2 \pi a}) \int_0^1 dx \frac{x^{a+1}}{x^4+6 x^2+1} - i \pi \frac{(\sqrt{2}-1)^{a} \left (e^{i \pi/2 (a+1)} - e^{i 3 \pi/2 (a+1)} \right )}{ \sqrt{2} }$$

Then

$$-i J'(0) = -i 8 \pi \int_0^1 dx \frac{x}{x^4+6 x^2+1} + \sqrt{2} \pi^2 - i \frac{2 \pi \log{(\sqrt{2}-1)}}{\sqrt{2}}$$

Now,

\begin{align}\int_0^1 dx \frac{x}{x^4+6 x^2+1} &= \frac12 \int_0^1 \frac{dx}{x^2+6 x+1}\\ &= \frac12 \frac1{x_+-x_-} \int_0^1 dx \, \left (\frac1{x-x_+}-\frac1{x-x_-} \right )\\ &= \frac12 \frac1{x_+-x_-} \left [\log{\left (\frac{x_-}{x_+}\frac{1-x_+}{1-x_-} \right )} \right ] \end{align}

where $x_{\pm}=-3 \pm 2 \sqrt{2}$ so that $x_+-x_- = 4 \sqrt{2}$. The argument of the log turns out to be $3 + 2 \sqrt{2} = (\sqrt{2}+1)^2$. Thus,

$$-i J'(0) = -i \sqrt{2} \pi \log{(\sqrt{2}+1)} + \sqrt{2} \pi^2 - i \sqrt{2} \pi \log{(\sqrt{2}-1)} = \sqrt{2} \pi^2$$

Thus,

$$\int_0^{2 \pi} dx \frac{x}{1+\cos^2{x}} = \sqrt{2} \pi^2$$

Now, we also need to evaluate

$$\int_0^{\pi} \frac{dx}{1+\cos^2{x}} = -i 2 \oint_{|z|=1} dz \frac{z}{z^4+6 z^2+1} = 4 \pi \cdot 2 \frac1{4 \cdot 2 \sqrt{2}} = \frac{\pi}{\sqrt{2}}$$

Thus, from the original relation derived above:

$$\int_0^{\pi} dx \frac{x}{1+\cos^2{x}} = \frac12 \left (\int_0^{2 \pi} dx \frac{x}{1+\cos^2{x}} - \pi \int_0^{\pi} dx \frac{1}{1+\cos^2{x}} \right ) = \frac{\pi^2}{2 \sqrt{2}}$$

which, of course, we could have obtained with one step if we just stuck with the symmetry argument. But hey, some of us love to see this done using the residue theorem over weird contours.

• Concise and most effective! +1 - Mark – Mark Viola Jan 21 '16 at 16:34
• it is interesting how hard this integral gets if one not uses symmetry – tired Jan 21 '16 at 16:55
• @tired: actually, I think this one isn't so bad in the complex plane. Need to mull it over a bit. – Ron Gordon Jan 21 '16 at 16:56
• @RonGordon Complex analysis works, but it seems to be quiet laborious – tired Jan 21 '16 at 16:58
• @RonGordon i wrote up something which is more or less elegant, i would really appreciate your comments – tired Jan 21 '16 at 17:59

Ok i think i found a way which is quiet different from the approaches above. It is based on the residue theorem using an rectangle with vertices $(0,0),(\pi,0),(\pi,\pi+ i R),(0, i R)$

Defining

$$f(z)=\frac{z}{1+\cos^2(z)}$$

We obtain

$$\oint dz f(z)=\underbrace{\int_0^{\pi}f(x)dx}_{I}+i\pi\underbrace{\int_0^{R}\frac{1}{1+\cosh^2(y)}dy}_{K}+\underbrace{i\int_0^{R}f(iy)dy+i\int_R^{0}f(iy)dy}_{=0}+\underbrace{\int_0^{\pi}f(iR+x)dx}_{J} =2\pi i\sum_j\text{Res}(f(z),z=z_j)$$

It is now easy to show that $J$ vanishs in the limit $R \rightarrow\infty$ and that $z_0=\arccos(-i)=\frac{\pi}{2}+i\log(1+\sqrt{2})$ is the only zero of the denominator of $f(z)$ inside the contour of integration. We are therefore down to

$$I=2\pi i \text{Res}(f(z),z=z_0)-i\pi K$$

the last integral can be computed by standard methods (Weierstrass subsitution)and yields $K=\frac{\text{arctanh}(\sqrt{2})}{\sqrt{2}}$. One may also show that $\text{Res}(f(z),z=z_0)=\frac{\log(1+\sqrt{2})}{2\sqrt{2}}-i \pi\frac{1}{4\sqrt{2}}$. Playling a little bit with the logarithmic representation of arctanh we find that the imaginary parts cancel (as they should) and we end up with

$$I=\frac{\pi^2}{2\sqrt{2}}$$

This numerically agrees with WA!

• tired: Actually, this is quite good. The complication lies with manipulating the logs and whatnot, but the analysis is solid. Good job! BTW I am putting together an alternative complex solution, I'll let you know when it is ready. – Ron Gordon Jan 22 '16 at 5:02
• tired: the solution is ready. Enjoy. – Ron Gordon Jan 22 '16 at 7:05


text:
# An Introduction to Recurrent Neural Networks & LSTMs

In this introductory guide we'll discuss recurrent neural networks (RNNs) and long short-term memory (LSTM) networks.

Let's jump into it:

A recurrent neural network attempts to model time-based or sequence-based data.

A few applications of recurrent neural networks include natural language processing (NLP), predicting stock prices, predicting energy demand.

To get a bit more technical, recurrent neural networks are designed to learn from sequences of data by passing the hidden state from one step in the sequence, to the next step, and combining this with the input.

This bring us to Long Short-Term Memory networks:

An LSTM network is a type of RNN that uses special units as well as standard units.

So what are these special units?

LSTM units include a 'memory cell' that can keep information in memory for long periods of time.

LSTMs are particularly useful when the neural network needs to switch between remembering recent things, and memory from a long time ago.

## RNNs vs. LSTMs

Let's say we have a regular neural network that is used for image recognition.

If we pass as image of a dog to the neural network - it will ideally output a high probability of being a dog, and maybe a small percentage chance of being a wolf, and a smaller chance of being a cat.

But what if the image was actually a wolf? How would the neural network know?

Now let's say that we have a sequence of images, say on a nature TV show, and the previous images were a wolf, a bear, and a fox.

What we do is analyze the images with the same copy of the neural network, but we use the output of the neural network as part of the the input of the next one.

This can improve our results.

To do this mathematically, we just combine the vectors in a linear function which will then be combined with an activation function - which could be either sigmoid or hyperbolic tan.

By doing it this way, the final neural network will know that the TV show is about wild animals that live in forests, and can use this information to predict the image is a wolf as opposed to a dog.

This is essentially how recurrent neural networks work.

The problem with recurrent neural networks is that the memory of the network is generally short-term memory.

For example if in between the bear and the wolf we had a flower and a tree (which could be thought of as either domestic of wild), the network would have a hard time remembering the significance of the bear and fox.

In short, RNNs have a hard time storing long term memory.

This is where long short-term memory, or LSTM networks save the day.

#### To recap, this is how an RNN works:

• Memory comes in and merges with a current event
• The output comes out as a prediction of what the input is
• The output is also part of the input of the next iteration of the neural network

In a similar way, an LSTM works as follows:

• It keeps track not just of short term memory, but also of long term memory
• In every step of the sequence, the long and short term memory in the step get merged
• From this, we get a new long term memory, short term memory, and prediction

By doing it this way, the network can remember things from a long time ago.

Now Let's look at the architecture of LSTMs.

### Basics of LSTM Networks

In our example of the nature TV show, we have:

• Long term memory about nature and forest animals
• Short term memory about flowers and trees
• An event - the image that could be a dog or wolf

We want to combine these things to create a prediction about what our image is.

The long term memory gives us a hint that the image should favor a wolf over a dog.

We also want all three variables to help us update the long term and short term memory of the network.

To define this, the architecture of the LSTM contains several gates:

• A forget gate
• A learn gate
• A remember gate
• And a use gate

#### Here's how they work together:

• The long term memory goes to the forget gate, where it forgets everything that's not useful
• The short term memory and the event are combined in the learn gate
• The long term memory we haven't forgotten plus the new information we learned get joined in the remember gate - which outputs an updated long term memory
• The use gate decides what information we use from what was already know plus what we just learned to make a prediction
• The output becomes both the prediction and the new short term memory

Now let's dive a bit deeper into the different gates.

#### The Forget Gate

• Takes the long term memory and decides what part to keep and what to forget

How does this work mathematically?

• The long-term memory (LTM) from time t-1 is multiplied by a forget factor ft.
• The forget factor is calculated with the short-term memory (STM) and the event information Et.
• We run a small one layer neural network with a linear function combined with the sigmoid function to calculate the forget factor.

#### The Remember Gate

• The remember gate takes the output from the Forget Gate and from the Learned Gate and we add them together.

#### The Use Gate

• Also called the output gate, this uses the long-term memory that came from the Forget Gate and the short-term memory from the Learned Gate to come up with a new short-term memory and an output (these are the same thing).

#### Here's how we do this mathematically:

• It applies a small neural network using the tanh activation function on the long-term memory
• It applies another small neural network on short-term memory and the events using the sigmoid activation function
• As a final step is multiplies these two together to get the new output

For a more in depth explanation of the mathematics of LSTM Networks I recommend this great video from Siraj Raval.

#### Character-wise RNNs

Character-wise RNNs are networks that learn text one character at a time, and generate new text one character at a time.

As an example we may want to generate new News Article Headlines, as this paper from Stanford discusses.

#### Sequence Batching

One of the hardest parts of building recurrent neural networks can be getting the batches right.

Let's walk through how batching works for RNNs:

• With RNNs we're training on sequences of data, such as text, audio, or stock prices
• By splitting the sequences into smaller sequences we can use matrix operations to improve the efficiency of training
• For example if we have a sequence of numbers from 0-10, we can either pass it in as one sequence, or we could split it into 2 sequences i.e. [0-4] and [5-10]
• The batch size corresponds to the number of sequences, so here the batch size would be 2

We also choose the length of the sequences we feed to the network, for example we could use the first 3 numbers of the sequence.

We can retain the hidden state from one batch and use it for the next one, thus the sequence information is transferred across batches for each mini-sequence.

### Summary: Recurrent Neural Networks & LSTMs

• RNNs are designed to learn from sequences of data by passing the hidden state from one step in the sequence to the next step and combining this with the input.
• LSTM networks are a type of RNN that use special units as well as standard units.
• LSTM units include a "memory cell" that can keep information in memory for long periods of time.
• LSTMs are particularly useful when our neural network needs to switch between remembering recent features, and features from a long time ago.

#### Further Resources

RNNs & LSTMs:

Coding Tutorials:

Join the conversation.