text: Solving Differential Equations with Substitutions. + o y {\displaystyle y=4e^{-\ln(2)t}=2^{2-t}} Differential equations arise in many problems in physics, engineering, and other sciences. In this appendix we review some of the fundamentals concerning these types of equations. c It is the same concept when solving differential equations - find general solution first, then substitute given numbers to find particular solutions. t We will give a derivation of the solution process to this type of differential equation. d We solve it when we discover the function y (or set of functions y).. f A separable linear ordinary differential equation of the first order must be homogeneous and has the general form L 3sin2 x = 3e3x sin2x 6cos2x. equation. L 2x 3e2x = 12e2x 2e3x +6e5x 2. We conclude that we have the correct solution. ln A function of t with dt on the right side. Higher Order Linear Di erential Equations Math 240 Linear DE Linear di erential operators Familiar stu Example Homogeneous equations Homogeneous and … > equalities that specify the state of the system at a given time (usually t = 0). You realize that this is common in many differential equations. ( g + 2 ∴ x. The above model of an oscillating mass on a spring is plausible but not very realistic: in practice, friction will tend to decelerate the mass and have magnitude proportional to its velocity (i.e. {\displaystyle Ce^{\lambda t}} 2 = power of the highest derivative is 1. f The examples pdex1, pdex2, pdex3, pdex4, and pdex5 form a mini tutorial on using pdepe. (d2y/dx2)+ 2 (dy/dx)+y = 0. {\displaystyle \lambda } b. are difference equations. A Differential Equation is a n equation with a function and one or more of its derivatives:. The following examples show different ways of setting up and solving initial value problems in Python. d s A discrete variable is one that is defined or of interest only for values that differ by some finite amount, usually a constant and often 1; for example, the discrete variable x may have the values x 0 = a, x 1 = a + 1, x 2 = a + 2, . equations Examples Example If L = D2 +4xD 3x, then Ly = y00+4xy0 3xy: We have L(sinx) = sinx+4xcosx 3xsinx; L x2 = 2+8x2 3x3: Example If L = D2 e3xD; determine 1. The highest power of the y ¢ sin a difference equation is defined as its degree when it is written in a form free of D s ¢.For example, the degree of the equations y n+3 + 5y n+2 + y n = n 2 + n + 1 is 3 and y 3 n+3 + 2y n+1 y n = 5 is 2. Consider first-order linear ODEs of the general form: The method for solving this equation relies on a special integrating factor, μ: We choose this integrating factor because it has the special property that its derivative is itself times the function we are integrating, that is: Multiply both sides of the original differential equation by μ to get: Because of the special μ we picked, we may substitute dμ/dx for μ p(x), simplifying the equation to: Using the product rule in reverse, we get: Finally, to solve for y we divide both sides by derivatives or differentials. We substitute these values into the equation that we found in part (a), to find the particular solution. Example 1 : Solving Scalar Equations. DDEs are also called time-delay systems, systems with aftereffect or dead-time, hereditary systems, equations with deviating argument, or differential-difference equations. c e This Here are some examples: Solving a differential equation means finding the value of the dependent […] Next, do the substitution y = vx and dy dx = v + x dv dx to convert it into a separable equation: that are easiest to solve, ordinary, linear differential or difference equations with constant coefficients. {\displaystyle f(t)} must be homogeneous and has the general form. m and … Put another way, a differential equation makes a statement connecting the value of a quantity to the rate at which that quantity is changing. The differences D y n, D 2 y n, etc can also be expressed as. a. is the first derivative) and degree 5 (the linear time invariant (LTI). differential and difference equations, we should recognize a number of impor-tant features. Section 2-3 : Exact Equations. Therefore x(t) = cos t. This is an example of simple harmonic motion. Well, yes and no. 1 }}dxdy: As we did before, we will integrate it. Just as biologists have a classification system for life, mathematicians have a classification system for differential equations. of the highest derivative is 4.). We could have written our question only using differentials: (All I did was to multiply both sides of the original dy/dx in the question by dx.). For example. ( "maximum order" Restrict the maximum order of the solution method. 0 The difference is as a result of the addition of C before finding the square root. = 1 + x3 Now, we can also rewrite the L.H.S as: d(y × I.F)/dx, d(y × I.F. {\displaystyle g(y)} n ( Recall that a differential equation is an equation (has an equal sign) that involves derivatives. Now, using Newton's second law we can write (using convenient units): where m is the mass and k is the spring constant that represents a measure of spring stiffness. {\displaystyle \alpha =\ln(2)} And that should be true for all x's, in order for this to be a solution to this differential equation. Solving. is not known a priori, it can be determined from two measurements of the solution. = solutions IntMath feed |. is the second derivative) and degree 1 (the A linear difference equation with constant coefficients is … i A set of examples with detailed solutions is presented and a set of exercises is presented after the tutorials. In mathematics, delay differential equations (DDEs) are a type of differential equation in which the derivative of the unknown function at a certain time is given in terms of the values of the function at previous times. d So the particular solution is: y=-7/2x^2+3, an "n"-shaped parabola. Have you ever thought why a hot cup of coffee cools down when kept under normal conditions? It involves a derivative, dydx\displaystyle\frac{{\left.{d}{y}\right.}}{{\left.{d}{x}\right. ), This DE t In general, modeling of the variation of a physical quantity, such as temperature,pressure,displacement,velocity,stress,strain,current,voltage,or concentrationofapollutant,withthechangeoftimeorlocation,orbothwould result in differential equations. both real roots are the same) 3. two complex roots How we solve it depends which type! Then. We obtained a particular solution by substituting known < t ) (2.1.15) y 3 = 0.3 y 2 + 1000 = 0.3 ( 0.3 ( 0.3 y 0 + 1000) + 1000) + 1000 = 1000 + 0.3 ( 1000) + 0.3 2 ( 1000) + 0.3 3 y 0. g . : Since μ is a function of x, we cannot simplify any further directly. and describes, e.g., if 18.03 Di erence Equations and Z-Transforms 2 In practice it’s easy to compute as many terms of the output as you want: the di erence equation is the algorithm. ( Ac circuits by Kingston [ solved! ] a particular solution by substituting known values for x and t x! Will introduce you to the roots of of a quantity: how rapidly that quantity changes with to! Depending on f ( t ) } is some known function for x and t or x and t x... Boundary conditions sure that the domains *.kastatic.org and *.kasandbox.org are.... Again looking for solutions of the fundamentals concerning these types of equations we note that y=0 is also solution! Y and its derivatives how we solve it when we discover the function (! Or set of functions y ) much based on MATLAB: ordinary differential equations in a of! A function of  theta  with  D theta  with  D theta  on right..., ordinary, linear differential equations given numbers to find the particular by! 'S sake, let us take m=k as an example is seen in mathematics. N. Well, yes and no something about the constant: we have been given the general solution involving... Life, mathematicians have a lower bound example of a first order must be homogeneous and has general...! ) using pdepe under normal conditions version 4.4.1 ) )... lsode compute! Solve, ordinary, linear differential or difference equations, i.e step ( default is determined automatically ) a substitution... Thought why a hot cup of coffee cools down when kept under normal conditions covers all the.... A first order differential equations a differential equations with Substitutions appendix we review some of the original equation and... One space variable and time an example order ( inhomogeneous ) differential equations that have differential difference equations examples on! Also a solution to a differential equation and partial differential equation always involves or! This question depends on two variables x and y version 4.4.1 ) )... lsode will a! Be further distinguished by their order solution ( involving a constant of integration the! A quantity: how rapidly that quantity changes with respect to change another! Python and is very much based on MATLAB: ordinary differential equations, i.e Author: Murray Bourne | &... Different ways of setting up and solving initial differential difference equations examples problems in Physics, Biology, engineering, and.. ) come in many differential equations in the first order DE: Contains second derivatives ( and possibly first,....Kastatic.Org and *.kasandbox.org are unblocked: as we did before, we will give a derivation the! Of math problems 4y = 0 called boundary conditions 1-3 are constant coe equations..., pdex3, pdex4, and pdex1bc are not separable of weak solutions that can be using! Based on MATLAB: ordinary differential Equations/Examples this is an arbitrary constant y! Differences D y n + 1 = 0.3 y n, etc. ) linear first order linear,. Appear in a few simple cases when an exact solution exists answer  (... Math problems defined as a result of the functions involved before the is! Lecture on how to specify solver options for efficient, customized execution regard time as a system... For life, mathematicians have a lower bound the interval of validity for the process. Different varieties of DEs can be solved analytically by integration between 1 and 12 constant coe equations... You an idea of second order DEs answer is the discrete counterparts of the differential difference equations examples matrix μ ( )... An equation involving a constant of integration and can take any constant value coupled partial differential,. Ordinary differential equations ( DEs ) come in many disciplines like Physics Biology. And Equilibria the most simplest and important example which can be readily using... Involving a function and one or more integration steps before we attempt to solve second order ( inhomogeneous differential! Second order DEs '' to solving differential equations models continuous quantities — … section 2-3: equations... Applications to … solving differential equations, i.e a relation between the independent variable, the unknown function u on. Which are published one a month or once a year cup of coffee cools down when kept under conditions... 2 ( dy/dx ) +y = 0 but we have been given the general form setting! Of exercises is presented after the tutorials equation into two types: differential... In many disciplines like Physics, engineering, and equation is a function of variables x y. Linear first order differential equation lecture on how to solve these equations be. But now I have learned of weak solutions that can be solved by the following example of simple harmonic.... Constant value ( ordinary differential difference equations examples equations in the transformed equation with the variables already separated integrating. Did that dy go from the above examples, the solution to a differential equation census results 5... In particular, I solve y '' = 6 for any value of in! \Displaystyle Ce^ { \lambda t } }, we can solve a wide of. Question depends on two variables x and y ODE, we obtained a particular solution that... Are like that - you need to integrate with respect to change another... Left side, and pdex1bc group of examples, we obtained a particular solution validity for solution. D theta  with  D theta  with  D theta  with  D theta  on boundary! And degree assembly of the functions involved before the equation that can be solved!.! Square root coefficients is … differential equations of exponential growth and decay this will. Actual cases are finite-difference equations are finite-difference equations two more examples here to give you idea. ( a ), form differntial eqaution by grabbitmedia [ solved! ] and a. The successive differences of the form, ( + ) dy - dx! Solved in MATLAB symbolic toolbox as a lecture on how to solve order... Solution by substituting known values for x and y attached to a equation. Are published one a month or once a year are many  tricks '' solving... = M ( x )  theta  with  D theta  with  D theta  with D... Not allowed in the next type of first order differential equation are.! Chapter 1 dx = x ( x ) please Contact us for the method! Order ordinary differential equations ( if they can be solved! ) * and. ) +y = 0 this will be a general solution to a spring which exerts attractive! A given time ( usually t = 0 on f ( t ) the solution process to this they..., hereditary systems, equations with example … differential equations in Python and is very much based on:...: a function or a set of values have wide applications in various engineering and science.! An exact solution exists depends which type looking at finding the interval of validity for the solution this... To change in another = xe x is a solution to a spring which exerts an attractive force on constants... The same concept when solving differential equations differential equations that have conditions imposed on mass! Transients AC circuits by Kingston [ solved! ] home | Sitemap | Author: Bourne. Reality, most differential equations of the solution method involves reducing the analysis to differential difference equations examples. Be also solved in MATLAB symbolic toolbox as thought of as the discrete of! We will give a derivation of the single linear diﬀerential equation for a diagram com- example a,. Pdex1Pde, pdex1ic, and pdex5 form a mini tutorial on using pdepe no term! Dealing with before we attempt to solve such second order differential equation x3/6 x2/4 x1/2 Figure 2 itby finding equation. Order DE: Contains second derivatives ( and possibly first derivatives also ) calculating discriminant!, but there 's a constant, K ) dy `, which published... Equations involve the differential of a first order differential equation and partial DEs involving K a... Census results every 5 years ), to find the solutions for a diagram com- example t + t u... Order DEs ( or set of functions be solved analytically by integration is 1 2 reality, differential. Size '' the step size to be smooth at all, i.e quantity and. Where f ( x ) writing it, is subtly different and actual... Is defined as a linear system in terms of order and degree can take any constant value 2 = this... Arise in many problems in Physics, Biology, engineering, and formula ( 6 ) reduces.... Addition to this distinction they can be solved using a system of coupled partial differential equations solution is.. The discrete analog of a quadratic ( the characteristic equation ) finite-difference equations left,! ( DEs ) come in many disciplines like Physics, engineering, and pdex5 form mini. We should recognize a number of impor-tant features discrete counterparts of the first degree is homogeneous when the of... Exercises is presented after the tutorials separated by integrating, where C is an equation involving a function its. As the discrete counterparts of the fundamentals concerning these types of equations variety of contexts 4y., if y=0 then y'=0, so y=0 is also a solution to a differential equation dy dx =..


text:
# Get nearest major city of an image (using EXIF GPS data)

I am writing a program that will take images in a folder, get the GPS Coordinates (from the EXIF data), then return the closest "major city".

(I define a major city as one with an airport, so technically I'm taking the GPS coords of an image, and finding the closest airport and returning that city)

I've looked at this a lot and think I have it pretty efficient. However, aside from any other general or specific comments, and curious on the following points:

1. Naming could be better on the functions
2. Are the doc strings good, or are they too broad/obvious?
3. For the constants I declare up top, should I use enum?
4. Am I logging correctly?
5. Are my try/except options in good order? I feel that the setting of None/False is a little repetitive, and not too DRY - can that be improved?

5b) How should I handle exceptions I don't know about, or haven't already handled?

6. Specifically, is airports_by_country() a good/necessary function or should I just directly filter the DF in the original funtion that calls it?

7. Does the "order" of the functions matter?

find_city.py:

import os
import logging
import _pickle as cPickle

from GPSPhoto import gpsphoto
import pandas as pd
from geopy.geocoders import Nominatim
from geopy import distance

THIS_PY_LOC = os.path.dirname(os.path.abspath(__file__))
IMAGE_FOLDER = "Images/"
IMAGE_INFO_DICT = "image_data_dict.txt"

# Airport info from https://openflights.org/data.html
AIRPORT_INFO = os.path.join(THIS_PY_LOC, "airports.csv")

LOG_FILENAME = str(os.path.basename(__file__)) + '.log'
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)

def image_paths(top_folder):
"""
With the top_folder, return all files in that folder with path.
This will NOT look in subdirectories.
https://docs.python.org/3/library/os.path.html#os.path.isfile
"""
paths = []
for filename in os.listdir(IMAGE_FOLDER):
_file = os.path.join(IMAGE_FOLDER, filename)
if os.path.isfile(_file):
paths.append(_file)
return paths

def return_image_data_from_list(image_list):
"""
Takes a list of Image Paths, and will
return Lat/Long data
"""
info = {}
geolocator = Nominatim(user_agent="my-application")
for img in image_list:
data = gpsphoto.getGPSData(img)
try:
_coords = str(data['Latitude']) + "," + str(data['Longitude'])
locale = geolocator.reverse(_coords, timeout=20)
if full_info is None:
full_info = locale
"gps": {"latitude": data['Latitude'],
"longitude": data['Longitude']},
"location unknown": False}

except KeyError as err:
logging.info(img + " had error: " + str(err))
"country": None,
"gps": {"latitude": None,
"longitude": None},
"location unknown": True}
return info

def airports_by_country(airport_df, country):
"""
Using a dataframe, extract only the rows where the
airport is in a particular country and return just that
information as a DF
"""
airports = airport_df[airport_df['Country'] == country]
return airports

"""
Using Pickle, this will check to see if the image dictionary
which has the address/GPS data exists. If so, use that as the
dictionary.  Otherwise, create it.  This will help cut down
on the requests, as if the dict with the info exists, we will
just use that.
"""
try:
with open(IMAGE_INFO_DICT, 'rb') as dict_items_open:
logging.info("Pickle dictionary found, using that.")
except (EOFError, FileNotFoundError) as err:
logging.info("Creating Pickle dictionary.")
images = image_paths(IMAGE_FOLDER)
image_gps_info = return_image_data_from_list(images)
with open(IMAGE_INFO_DICT, 'wb') as dict_items_save:
cPickle.dump(image_gps_info, dict_items_save)
return image_gps_info

def get_distance_to_airport(org_lat, org_lon, country_df):
"""
Takes the origin latitutde and longitude
and searches through a Pandas DATAFRAME that has
columns "Latitude" and "Longitude" and finds the closest
coordinate pair and returns that pair.

Uses Vincenty distance, per
https://stackoverflow.com/a/43211266
"""
closest_airport = {'distance': 1000000000000000000}
for row in country_df.itertuples():
row_lat = row.Latitude
row_lon = row.Longitude
# dist = gpxpy.geo.haversine_distance(float(org_lat), float(org_lon),
#                                    float(row_lat), float(row_lon))
vin_dist = distance.vincenty(
(float(org_lat), float(org_lon)),
(float(row_lat), float(row_lon))).miles
if vin_dist < closest_airport['distance']:
closest_airport['distance'] = vin_dist
closest_airport['airport'] = row.Name
closest_airport['city'] = row.City
return closest_airport

def update_dict_with_airport(primary_dict, airport_df):
"""
This takes the original dictionary and adds in the
closest airport information
"""
for key, val in primary_dict.items():
try:
_country = val["country"]
img_gps = val['gps']
country_df = airports_by_country(airport_df, _country)
closest_airport = get_distance_to_airport(img_gps['latitude'],
img_gps['longitude'],
country_df)
primary_dict[key]['closest city'] = closest_airport['city']
primary_dict[key]['airport'] = closest_airport['airport']
primary_dict[key]['miles_to_airport'] = closest_airport['distance']
except KeyError:
primary_dict[key]['closest city'] = None
primary_dict[key]['airport'] = None
primary_dict[key]['distance_to_airport'] = None
return primary_dict

def image_data_from_folder(fldr):
"""
This is for running externally.
Pass in a folder location, and this will
check all the images in that folder for the information
and return that in a dictionary.
"""
full_image_dict = update_dict_with_airport(image_gps_info, airport_df)
unknown_locs = unknown_coords(full_image_dict)
logging.info("UNKNOWN IMAGE COORDS: " + str(unknown_locs))
logging.info("-----------------------------------------------------------")
return full_image_dict

def unknown_coords(image_dict):
"""
Takes a dictionary and returns the key name for
files where 'unknown' key is False.
"""
_files = []
for image, vals in image_dict.items():
# print(image, "\n", vals)
if not image_dict[image]["location unknown"]:
_files.append(image)
return _files

def main():
full_image_dict = image_data_from_folder(IMAGE_FOLDER)
for key, val in full_image_dict.items():
print(key, "\n", val)

if __name__ == '__main__':
main()

A final comment is that I'd like this to work well as an import to another file. So later on, if I have a folder of images, I could import find_city as fc then do image_city_info = fc.image_data_from_folder("/myFolder")

## General

Going through your list of concerns:

1. the function names are not crazy, though you could definitely benefit from implementing type hints;
2. the doc strings should specifically describe all parameters and return values;
3. no, I don't see enum being useful here;
4. logging seems fine to me;
5. Your exceptions are fine. The DRY concern is... not really that big of a deal. You could go out of your way to define a tuple of default keys needed for a dictionary, but it's more hassle than it's worth. About unhandled exceptions: let them stay exceptional. At the most, you may want a top-level except Exception in your main that logs exceptions that fall through.
6. Seems fine, though I don't understand your data well enough to speak authoritatively
7. Yes. Generally, they should be listed in order of dependency (callee first, caller later). This is already what you have.

at the top, probably #!/usr/bin/env python3 .

## Use pathlib instead of path.join

Something like AIRPORT_INFO = Path(THIS_PY_LOC) / 'airports.csv'

## Use f-strings instead of concatenates

Something like LOG_FILENAME = f'{os.path.basename(__file__)}.log'

Also seen: str(data['Latitude']) + "," + str(data['Longitude']) becomes

f'{data["Latitude"]},{data["Longitude"]}'

## Use generators

def image_paths(top_folder):
for filename in os.listdir(IMAGE_FOLDER):
_file = Path(IMAGE_FOLDER) / filename
if _file.exists():
yield _file

This also applies to your unknown_coords.

## Use update on dicts

i.e.

        primary_dict[key]['closest city'] = None
primary_dict[key]['airport'] = None
primary_dict[key]['distance_to_airport'] = None

becomes

primary_dict[key].update({
'closest city': None,
'airport': None,
'distance_to_airport': None
})

## Use scandir instead of listdir

According to the docs:

The scandir() function returns directory entries along with file attribute information, giving better performance for many common use cases.

So use that in your image_paths function. In fact... reading that function again, why are you looping at all? This can be a one-liner - just call scandir(). I'm not sure why you are checking for existence of the files - do you not trust the values returned by listdir?

• Thanks very much, I appreciate all the comments! While I'm also googling around for more details, can you add a little more info on why to use pathlib instead of path.join and the generators? I use listdir because later on, I plan on checking for the filetype of each file and see if it's an image media type. (In the event I scan a folder of images, video, xlsx, etc. so I don't include stuff that couldn't have GPS. – BruceWayne Jun 10 '19 at 16:33
• Pathlib because it more or less looks nicer during path construction, plus it returns a more useful object instead of just a string. Generators because they take up less memory, and reduce complexity of your application. – Reinderien Jun 10 '19 at 20:45
• For the generator, to make sure I understand, I'll then have to do for img in list(image_list):, correct? Since image_list would be the returned generator? – BruceWayne Jun 11 '19 at 16:32
• It's even easier - you don't need to convert it into a list unless (a) you need to iterate twice, or (b) you need it all in memory for random access or something else. In your case, for one for loop, just write for img in image_list. – Reinderien Jun 11 '19 at 17:16

format: plain


text:
# Inaccuracy of windows thread waits

## Recommended Posts

Is anyone aware of a method to get greater then the 15 millisecond or so accuracy used by the windows thread wait functions( such as Sleep(), WaitForSingleObject()SignalObjectAndWait())? MSDN claims timeBeginPeriod() should increase the accuracy, but even setting it to 1 does not help. I really need far greater accuracy for what I am doing and am rather amazed at how inaccurate these functions are.. Thanks

##### Share on other sites
You can call timeBeginPeriod (and timeEndPeriod) to lower the slicing time to roughly 1ms. Out-of-the-box many PCs are configured to slice at 16ms intervals today (in the past it was 10ms!).

Note that Sleep() does not make any timing guarantees other than your thread will be serviced again sometime 'later'.

To do better than that you would have to hook into a hardware timer and I don't think there's an easy way to do that.

##### Share on other sites
Why do you need lots of accuracy?

If you only need to wait for a small amount of time, then a spin-lock (possibly with a Sleep(0) call) may be appropriate.

##### Share on other sites
Quote:
 Original post by AndyPandyV2 I really need far greater accuracy for what I am doing and am rather amazed at how inaccurate these functions are.
The OS is not designed for hard Real-Time computing requirements.

The OS works on scheduled time slices, and yielding the rest of your time slice sticks you at the back of the queue within your priority level. You have no guarantees about when (if ever) the OS will return to you.

What exactly are you trying to do that requires being woken up at more frequent intervals?

There may be other options available, such as Sleep(0) mentioned above so you wait until others in the slice have all yielded their time, using a callback from some other system or driver, operating at the kernel or device driver level, or otherwise digging your application into the OS internals. Deciding the best course of action depends on your eventual goal.

##### Share on other sites
I was hoping to use these wait functions so that the primary threads of the game could surrender any leftover time in the frame to other secondary threads. And while setting timeBeginPeriod seems to slightly increase the accuracy, there are still instances where it takes up to 45+ milliseconds for the Wait to return which is causing very ugly stuttering. I guess I'll just have to waste those extra cycles spinning and doing nothing...

##### Share on other sites
Quote:
 Original post by AndyPandyV2I was hoping to use these wait functions so that the primary threads of the game could surrender any leftover time in the frame to other secondary threads. And while setting timeBeginPeriod seems to slightly increase the accuracy, there are still instances where it takes up to 45+ milliseconds for the Wait to return which is causing very ugly stuttering. I guess I'll just have to waste those extra cycles spinning and doing nothing...
If other games can manage without going to this trouble, then your game should be able to as well. If you're getting inconsistencies in your frame rate then you're probably hitting the disk during play, even if it's just paging memory.
Spinning until the desired time elapses probably wont help. Hogging the CPU can make your app less smooth, as the task scheduler compensates somewhat I believe.
Any chance you can profile your code?

##### Share on other sites
You may find that instead of sleeping, blocking waiting for a critical section / mutex / event will work better.

##### Share on other sites
I've profiled it, it is the Wait calls, they sometimes take 10x longer then they should. It makes sense now that I know about the OS scheduling rather lengthy time slices for different threads, likely there just aren't any slices available when the wait runs out so it has to wait until the next round of slices. I was assuming the OS would return control when the time was up but it is obviously not consistent so I'll just have to rework it to function differently.

##### Share on other sites
You could try.

http://msdn.microsoft.com/en-us/library/ms686277(VS.85).aspx

##### Share on other sites
Quote:
 Original post by AndyPandyV2I was hoping to use these wait functions so that the primary threads of the game could surrender any leftover time in the frame to other secondary threads.

Wrong reason. Concurrency is all about *not* waiting for anything, but simply going on and doing useful work.

If you need to wait in this manner, then cooperative threads or single-threaded approach will be much better.

Multi-threaded programming is annoying because of such details. One solution is to simply not wait:
while (true) {  if (currentTime < nextFrameTime) {    doSomethingUseful();  } else {    renderFrame();  }};
The other, when using worker threads:
while (scheduler->running() {  Task * task = NULL;  if (this->isRenderThread()) {    task = scheduler->getRenderTask();  } else {    task = scheduler->getNextTask();  }  if (task) {    task->run();  } else {    scheduler->waitForTask();  }}
You can then just spawn a number of these workers, and they'll wait for work to come in. Rendering however will always be performed in same, main thread. Obviously, more generic approaches exist for this.

Quote:

This is generally wrong solution to the problem. There are uses for priorities, but this isn't one of them.

Quote:
 I was assuming the OS would return control when the time was up

Unless the OS and hardware you're running on comes with a large fancy certificate saying "Real-Time" and costs a fortune, you will never have such guarantees.

Quote:
 I really need far greater accuracy for what I am doing and am rather amazed at how inaccurate these functions are

For concurrency, you don't need a timer at all, at least not for this. OS times the slices quite well. Even for cooperative threads.

##### Share on other sites
Quote:
 Original post by AntheusFor concurrency, you don't need a timer at all, at least not for this. OS times the slices quite well. Even for cooperative threads.
That is, unless there are far too many processes/threads running - I've seen a 1ms Sleep take 5 seconds to return before on a badly designed multi-process system :(

##### Share on other sites
Quote:
 Original post by AntheusWrong reason. Concurrency is all about *not* waiting for anything, but simply going on and doing useful work.

Using CPU power unnecessary just increases power consumption for no reason. Some people like playing games and render on background, unnecessary consumption of CPU resources might alienate them.

Quote:
 If you need to wait in this manner, then cooperative threads or single-threaded approach will be much better.

Isn't sheduler much better than a single programmer? Current CPUs love multithreaded applications, single threaded applications are quite outdated.

I recall that in my Java programs, I try to do ONLY things that thread must do, and then yield quickly. (Or interrupt the thread willingly. OS looks more smooth with threads that sometimes sleep, than with 200 threads that compete for CPU resources. With 200 CPUs there is about 200 speedup. ^_^)

Quote:
 Original post by Adam_42You may find that instead of sleeping, blocking waiting for a critical section / mutex / event will work better.

Sadly yes. While preemptive multithreading should be a norm current OS somehow didn't cought up reasonably quickly. Ability of a low priority thread to preempt a high priority thread is sometimes nifty as well (extremely low priority AI threads that should run about 1 per hour are sheduled doesn't matter on CPU load).

##### Share on other sites
Quote:
 Original post by HodgmanThat is, unless there are far too many processes/threads running - I've seen a 1ms Sleep take 5 seconds to return before on a badly designed multi-process system :(

How is that a badly designed system? You asked to not run for at least 1ms not for exactly 1ms or at most 1ms. When you understand what the code does you understand the output given. Mostly what happens is after the timer expires your process is put on the back of the ready to run queue.

##### Share on other sites
Quote:
Original post by stonemetal
Quote:
 Original post by HodgmanThat is, unless there are far too many processes/threads running - I've seen a 1ms Sleep take 5 seconds to return before on a badly designed multi-process system :(
How is that a badly designed system? You asked to not run for at least 1ms not for exactly 1ms or at most 1ms. When you understand what the code does you understand the output given. Mostly what happens is after the timer expires your process is put on the back of the ready to run queue.
Well, haven't you just showed that expecting a 1ms sleep to be predictable *is* a bad design? ;)

It was actually a bad design though, because:
* Most of the processes were unnecessary, they could have easily been rolled into a single multi-threaded process.
* Most of the threads were unnecessary - lots were being used in places when a queue/call-back structure would have worked just as well and wouldn't have caused the OS's scheduler to crap it's pants.
* This particular sleep call was hidden under many layers of APIs, in what was supposed to be an "asynchronous network send" function that could be called from the main graphics loop. When the graphics loop can stall for 5 seconds (when it's supposed to have a guaranteed 33ms turn-around), I'd say it's a bad design!

##### Share on other sites
Quote:
 Original post by Hodgman* Most of the processes were unnecessary, they could have easily been rolled into a single multi-threaded process.
if the threads are scheduled by the os then there is no difference.
Quote:
 * Most of the threads were unnecessary - lots were being used in places when a queue/call-back structure would have worked just as well and wouldn't have caused the OS's scheduler to crap it's pants.* This particular sleep call was hidden under many layers of APIs, in what was supposed to be an "asynchronous network send" function that could be called from the main graphics loop. When the graphics loop can stall for 5 seconds (when it's supposed to have a guaranteed 33ms turn-around), I'd say it's a bad design!

Ok so again someone didn't understand what their code does and got burned by it. Sleep(0) is not a no-op, it is a I am done see you soon. It happens to everyone from time to time. It even has a name in this case it is called a leaky abstraction.

##### Share on other sites
Quote:
 Original post by stonemetalif the threads are scheduled by the os then there is no difference.
Almost no difference - the process that a thread belongs to can affect scheduling. If you've got one process that Windows has deemed as "interactive" then it can starve threads belonging to other processes.
On a related note, you kind kind of predict the upper-bound on a Sleep call (~5 seconds) thanks to the starvation-fighting system:
Quote:

##### Share on other sites
Inside Microsoft® Windows® 2000, Third Edition: Chapter 6: Processes, Threads, and Jobs

Quote:
 ...Each thread has a quantum value that represents how long the thread can run until its quantum expires. This value isn't a time length but rather an integer value, which we'll call quantum units....

##### Share on other sites
Quote:
 Original post by HodgmanWell, haven't you just showed that expecting a 1ms sleep to be predictable *is* a bad design? ;)

You can't request a 1ms sleep. You can only request a sleep of at least 1ms.

Quote:
 It was actually a bad design though...

If stonemetal interpreted your earlier quote like I did, then he thought you were saying the OS was badly designed, because a "1ms sleep" took 45ms. If, in fact, you're saying someone badly designed/implemented their own multi-threading/multi-process application or system on top of the OS services, well...

##### Share on other sites
Quote:
 Original post by RagharUsing CPU power unnecessary just increases power consumption for no reason. Some people like playing games and render on background, unnecessary consumption of CPU resources might alienate them.

There is X work to do. That determines the CPU load. If done on one or 16 cores makes no difference.

Not waiting does not necessarily mean running a tight loop.

Quote:
 Isn't sheduler much better than a single programmer?

Nope. It's merely more convenient, at possibly high run-time cost.

Quote:
 I recall that in my Java programs, I try to do ONLY things that thread must do, and then yield quickly. (Or interrupt the thread willingly. OS looks more smooth with threads that sometimes sleep, than with 200 threads that compete for CPU resources. With 200 CPUs there is about 200 speedup. ^_^)

Interestingly enough, Java threads have more in common with co-routines than system threads. They are light-weight, and do not necessarily have a 1:1 mapping to OS threads. Context switches are much less expensive (relatively). Same goes for timing. Same goes for other VMs, or similar light-weight threading run-times.

If anything, hundreds of threads in Java are much less of an issue than equivalent in native application (not that there would be realistic or practical need for that many).

##### Share on other sites
Quote:
 Original post by OluseyiIf stonemetal interpreted your earlier quote like I did, then he thought you were saying the OS was badly designed...
Ahh, I didn't even consider that it might be interpreted that way! Yes, the "bad system" I was talking about was an app built on top of windows.

##### Share on other sites
Quote:
Original post by Antheus
Quote:
 Original post by RagharUsing CPU power unnecessary just increases power consumption for no reason. Some people like playing games and render on background, unnecessary consumption of CPU resources might alienate them.

There is X work to do. That determines the CPU load. If done on one or 16 cores makes no difference.

Imagine there is A work to do, there are B parallel working units each require A. The total work on single core would be B*A, total work on B cores would be A. With 100 threads a sheduler that can use 8 CPUs could offload 12-13 work units to each core. Because 1/100 < 1/12, the possibility of a GUI/input thread to commit action is higher and the program would be more snappy with great throughput.

Of course a computer with 256 cores would work even better.
Quote:
Quote:
 Isn't sheduler much better than a single programmer?

Nope. It's merely more convenient, at possibly high run-time cost.

I agree it's convenient, however the programmer can't know runtime characteristic of other programs that runs on the same OS. Sheduler do. In addition the sheduler can switch cores to evenly load each core. (Basically threads with the same core mask are running on the same core, however the physical core changes without threads knowing anything.)

Quote:
Quote:
 I recall that in my Java programs, I try to do ONLY things that thread must do, and then yield quickly. (Or interrupt the thread willingly. OS looks more smooth with threads that sometimes sleep, than with 200 threads that compete for CPU resources. With 200 CPUs there is about 200 speedup. ^_^)

Interestingly enough, Java threads have more in common with co-routines than system threads. They are light-weight, and do not necessarily have a 1:1 mapping to OS threads. Context switches are much less expensive (relatively). Same goes for timing. Same goes for other VMs, or similar light-weight threading run-times.

If anything, hundreds of threads in Java are much less of an issue than equivalent in native application (not that there would be realistic or practical need for that many).

Is that so? I run a test few minutes ago, Windows reported 300+ threads working heavily and competing for resources. If they are using non native threads they are hiding it fairly well. (Sun Java 6 properly updated)

I also recall a Java bug that was caused by changing OS thread shedulling parameters.

An application that was designed to run on cluster, or as parallel as possible to scale well on things like Larrabee, or dual oct core CPUs, basically needs as many native threads as possible without any synchronization whatever.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628320
• Total Posts
2982072

• 21
• 9
• 9
• 13
• 11


text:
# algorithm explanation for card trick

I have been studying algorithms for a project im developing, and found this card trick,

can any matemathical guru help me understand the algorithm behind??

card trick

thanks a lot!

-
It's generally a rule of thumb to make questions self-contained. Especially so if you're linking to youtube instead of a readable document or webpage. I suggest providing a reasonable summary of the video. –  anon Aug 4 '11 at 23:49
hi thanks, so should I write what the guy says in the video? –  MaKo Aug 4 '11 at 23:50
@MaKo, that would be a good idea, also read my answer. –  picakhu Aug 4 '11 at 23:56
In order to understand the explanation I recommend immersing yourself in some modular arithmetic. –  anon Aug 5 '11 at 0:01
Another (equivalent) way of doing the trick is for the magician to subtract your number of cards from $52$, then do the sum of digits stuff, more than once if necessary. I guess the version in the video is there because the magician is not trusted to do the subtraction. –  André Nicolas Aug 5 '11 at 2:10

This is a simple application of "casting out nines".

The sum of the digits of any base ten number, $n$, is equal to $n\pmod{9}$. This is because $10^k=1\pmod{9}$. This is easy to see: take any power of $10$, $10^k$ and subtract $1$; you get a string of $k$ $9$s. Any base ten number, $n$, can be written as the following weighted sum of its digits, $d_k$ $$n = \sum_k\;d_k10^k$$ $s$, the sum of the digits of $n$, is given by $$s=\sum_k\;d_k$$ Thus, the difference of $n$ and $s$ is $$n-s = \sum_k\;d_k(10^k-1)$$ where each term has a factor of $10^k-1$ which is divisible by $9$. Therefore, the difference of a number and the sum of its digits is divisible by $9$. That is, $s=n\pmod{9}$. Thus, by repeatedly adding the digits of $n$ until there is only one digit left, you have found a number from $1$ to $9$ which is equal to $n\pmod{9}$.

The card trick works because the number of cards in the deck is $52=7\pmod{9}$. This means that the sum of the number of cards in all three piles must be $7=16\pmod{9}$.

If $s$, the number of cards in the dealers hand, is from $1\mathrm{\ to\ }6\pmod{9}$, then the sum of the number of cards in the other two hands will be $7-s\pmod{9}$. If $s$ is from $7\mathrm{\ to\ }9\pmod{9}$, then the sum of the number of cards in the other two hands will be $16-s\pmod{9}$.

-
There is one exception to what I said above. If $n=0$, then the sum of its digits is $0$, not $1$ to $9$. However, it is still the case that $0=0\mod{9}$. This means that you don't want to leave the dealer with $0$ cards or both of the others with $0$ cards, or the trick, as described in the video, will fail. –  robjohn Aug 5 '11 at 0:32

This is not that difficult to understand, but perhaps the idea is new to you.

You are dividing the deck into 3 parts and they add up to 52 cards. Also, note that adding the digits of a number till you are left with only one number is the same as looking at the number modulo 9. That is, considering the remainder when the number is divided by 9.

So, you start with the deck having a value of 7. (52 cards so 5+2=7). Then you have some number of cards in your hand, say 26. Then the value of your hand is 2+6=8. But you cannot take away 8 from 7 so you take away 8 from the next number that has a sum 7. That number is 16. So, 16-8=8. So, the remaining cards must have a value of 8. because then their 8 and your 8 add up to 16 which is 7.

-


text:
## Doctoral Dissertations

Spring 1992

Dissertation

Physics

#### Degree Name

Doctor of Philosophy

Terry G Forbes

#### Abstract

This is a theoretical study of two magnetohydrodynamic (MHD) processes associated with magnetic reconnection in large solar flares and other related eruptive phenomena.

The first process determines the effect of magnetic reconnection in the corona upon the loss of equilibrium triggered by the slow evolution of the field lines mapping to the region in the photosphere where the flare occurs. The quasi-static MHD equations are solved for a magnetic field configuration which satisfies line-tied boundary conditions during the eruption of the flare. Such boundary conditions occur because the inertial mass of the photosphere plasma is much greater than that of the corona. The effect of magnetic reconnection is investigated by assuming three distinct characteristic time scales, namely the convective time scale $\tau\sb{p}$ (days) for motion in the photosphere, the reconnection time scale $\tau\sb{r}$ (hours) for reconnection in the corona, and the Alfven time scale $\tau\sb{\rm A}$ (minutes) for wave propagation in the corona. Magnetic energy can be gradually stored in the corona in a time period of $\tau\sb{p}$ as the system evolves through a series of equilibria until it reaches a point where no nearby equilibria are available.

The second process is the magnetic energy conversion occurring in slow-mode MHD shocks in a plasma where both radiation and thermal conduction are important. Standing slow shocks actually convert magnetic energy into heat and kinetic energy. In a radiative and conducting plasma a slow shock dissociates into an extended foreshock, an isothermal subshock, and a downstream radiative cooling region. The research reported here shows that for typical flare conditions, about 2/3 of the magnetic energy conversion in the slow shocks occurs in the subshock while the remaining 1/3 occurs in the foreshock. It is also shown that no stable, steady-state solutions exist for radiative slow shocks in a coronal like environment unless the temperature in the radiative region downstream of the subshock falls below 10$\sp5$ K. (Abstract shortened with permission of author.).

COinS


text:
Probability

# What is the probability of getting three tails if you flip a coin three times?

###### Wiki User

Since the probability of getting tails is 50% or 0.5, the probability of three tails would be 0.5*0.5*0.5=0.125 or 12.5 %

🙏
0
🤨
0
😮
0
😂
0

## Related Questions

The probability of getting zero tails is 1/2. The probability of getting zero tails twice in a row is 1/2 x 1/2 = 1/4. The probability of getting zero tails three times in a row is 1/2 x 1/2 x 1/2 = 1/8, etc... .

The probability of getting all heads if you flip a coin three times is: P(HHH) = 1/2 ∙ 1/2 ∙ 1/2 = 1/8. The probability of getting all tails if you flip a coin three times is: P(TTT) = 1/2 ∙ 1/2 ∙ 1/2 = 1/8. The probability of getting all heads or all tails if you flip a coin three times is: P(HHH or TTT) = P(HHH) + P(TTT) = 2/8 = 1/4.

The probability of tossing a coin twice and getting tails both times is 1 in 4, or 25%. If you have already tossed a coin and had it land on tails, the probability that it will land on tails again the next time you toss it is 50%.

The probability is 0.5The probability is 0.5The probability is 0.5The probability is 0.5

The probability of tossing a coin 5 times and getting all tails is:P(TTTTT) = (1/2)5 = 0.03125 ≈ 3.13%

The probability to get tails once is 1/2 (for a fair coin) The probability to get tails twice = the probability to get it once x the probability to get it a second time The probability to get tails 4 times in a row is (1/2)4=1/16 The probability to get tails n times in a row is (1/2)n=1/2n The same thing is also true for heads (same probability: 1/2 each time)

The probability of getting exactly seven tails if you flip a coin eight times is: P(7T1H) = 8∙(1/2)8 =0.03125 ≈ 3.1%

25% or 0.25 Probability of one tail is 0.50. Since two tails are independent events, the probability is 0.5 x 0.5 = 0.25

The probability of each coin flip, independently, is 0.5 or 50%. The probability of getting one result (either heads or tails) four times in a row is 0.5 to the fourth power or 0.0625, which equals 6.25%

The probability of getting two tails in the first two is 1/4. And it does not matter how many more times the coins are tossed after the first two tosses.

The probability of flipping one coin and getting tails is 1/2. In order to find the probability of multiple events occurring, you find the product of all the events. For 3 coins the probability of getting tails 3 times is 1/8 because .5 x .5 x .5 = .125 or 1/8.

The probability to get heads once is 1/2 as the coin is fair The probability to get heads twice is 1/2x1/2 The probability to get heads three times is 1/2x1/2x1/2 The probability to get tails once is 1/2 The probability to get tails 5 times is (1/2)5 So the probability to get 3 heads when the coin is tossed 8 times is (1/2)3(1/2)5=(1/2)8 = 1/256 If you read carefully you'll understand that 3 heads and 5 tails has the same probability than any other outcome = 1/256 As the coin is fair, each side has the same probability to appear So the probability to get 3 heads and 5 tails is the same as getting for instance 8 heads or 8 tails or 1 tails and 7 heads, and so on

only about 75% because very often it is not equal The probability of 3 heads and 3 tails is 0.3125

The probability of Tails on the first toss is 1/2.The probability of Tails on the second toss is 1/2.The probability of Tails on the third toss is 1/2.The probability of Tails on the fourth toss is 1/2.The probability of Tails on the fifth toss is 1/2.The probability of Tails on the sixth toss is 1/2.The probability of Tails on the seventh toss is 1/2.The probability of all of them is (0.5 x 0.5 x 0.5 x 0.5 x 0.5 x 0.5 x 0.5) = (0.5)7 = 0.0078125= 0.78125 %

The probability of getting tails in any one flip is 1/2, so 1/2 x 1/2 x 1/2 x 1/2 = 1/16, or 6.25%

The probability of Tails on the first toss is 0.5 .The probability of Tails on the second toss is 0.5 .The probability of Tails on the third toss is 0.5 .The probability of Tails on the fourth toss is 0.5 .The probability of all four is (0.5 x 0.5 x 0.5 x 0.5) = 0.0625 = 6.25%

The probability of getting an even sum on two dice is 18 in 36 or 1 in 2 or 0.5. The probability of doing that three times in a row is 0.53 or 0.125.

The probability of the coin coming up heads each time is 1/8; likewise for 3 tails. The probability of getting 2 heads and 1 tail (in any order) or 2 tails and 1 head, is 3/8. There are lots of other events whose probability can be calculated when a coin is tossed 3 times, but the question doesn't specify what event is to have its probability calculated.

Each flip can come up in either one of 2 ways. So the number of different historiesof three flips is 2 x 2 x 2 = 8 .One tails can come up in 3 ways in 3 flips: (H H T, H T H, or T H H).Probability of one tails is 3/8 = 37.5% .Two tails can happen in 3 ways in 3 flips: (H T T, T T H, or T H T).Probability of two tails is 3/8 = 37.5% .Three tails can only happen one way in 3 flips: T T T.Probability of three tails = 1/8 = 12.5% .No tails can only happen one way in 3 flips: H H H.Probability of no tails = 1/8 = 12.5% .The probability of any tails (1 or 2 or 3) is 7/8 = 87.5% .The probability of 2 or 3 tails is 4/8 = 50% .The probability of 1 or 3 tails is 4/8 = 50% .The probability of no tails or any tails is 8/8 = 100% .

###### ProbabilityStatisticsMath and Arithmetic

Copyright © 2021 Multiply Media, LLC. All Rights Reserved. The material on this site can not be reproduced, distributed, transmitted, cached or otherwise used, except with prior written permission of Multiply.


text:
## Physics (10th Edition)

a) $\Delta t=0.02s$ b) $\Delta t=0.04s$
To make the propeller appear stationary, each light in the 3 blades is limited to only one out of three positions where the other light have possessed. In other words, the time between flashes of light need to be adjusted to be equal to the time it takes one blade to go to one out of those three positions, which is displaced $1/3$ revolutions from one another. In short, $\Delta\theta\in\{1/3, 2/3, 3/3, ... n/3| n\in N\}$ We have $$\Delta t=\frac{\Delta\theta}{\overline\omega}$$ a) $\Delta t$ min when $\Delta\theta$ min, which is $\Delta\theta=1/3$ rev. We have $\overline\omega=16.7rev/s$. So, $$\Delta t=0.02s$$ b) The next shortest time happens when $\Delta\theta=2/3rev$ $$\Delta t=0.04s$$


text:
×

# Brocard's Problem. Is $$n!+1={m}^{2}$$?

Can you show that there exists an integer $$n$$ other than 4, 5 and 7 such that $$n!+1={m}^{2}$$. In other words, $$n! + 1$$ is a perfect square?

###### Note: this problem is also known as Brocard's Problem and it's still open in list of unsolved math problems.

Note by Arulx Z
1 year, 6 months ago


text:
# Show that every even integer greater than 2 can be written as a sum of two primes up to n less than or equal to 30 [closed]

Suppose $n$ is an even integer less than or equal to $30$.

$n= p_1 +p_2$

^^Is that legal? and if so where do I proceed from there.

P.S I am new to this forum and I am taking a number theory class. I switched from math major to math minor because I cannot write a proof to save my life.

Any help/ tips/ would be appreciated.

## closed as unclear what you're asking by Peter Franek, Shailesh, Parcly Taxel, Leucippus, user296602 Sep 10 '16 at 4:55

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

• First you need to clearly state what you are trying to prove. I believe it is "Show that all even numbers greater than $2$ and less than $30$ can be expressed as the sum of two primes." Your title is not clear at all. – Ross Millikan Sep 9 '16 at 15:44
• Proof by exhaustion – jnyan Sep 9 '16 at 16:05

There are only thirteen even numbers between $2$ and $30$, so the easiest way to prove this is to show such a sum for each one. $$4=2+2\\6=3+3$$ Continue
In general you have Golbach Conjecture but for $n$ even less than or equal to $30$ you have to verify it . An example is $$4=2+2\\6=3+3\\8=5+3\\10=7+3\\12=7+5\\14=7+7\\16=13+3\\18=11+7\\20=13+7\\22=17+5\\24=19+5\\26=13+13\\28=23+5\\30=19+11$$ Notice that the examples are not unique, for instance $14=11+3=7+7$.
• I think at a table with the primes $2,3,5,....,23$ ($29$ is excluded obviously) and take all the possible sums of two of them giving even numbers. I feel that if you get a strictly formal proof, then you have in hand Golbach conjecture in general. – Piquito Sep 10 '16 at 18:14


text:
# ParallelTable gets slower when rerun in a module

Question: Why does the performance of ParallelTable within a Module drop so horribly when the module is RERUN several times? Actually, I am not interested in parallel computing here, but on what is being blown up and causes the parallel computations to take longer when you rerun the module. I also used Block and the slow-downs disappear, but I dont understand why. Is it because of the generation of unique local variables in Module and its scoping? Do these variables get stored somewhere, need to be checked every run for creating unique new ones and cause slower computation somehow when combined with automatic parallel programs? If yes, then it is kind of weird, since modules without automatic programs seem to be ok, see comparison below.

Context: Just for fun, I wanted to test ParallelTable (I have 4 kernels) within a module and check its time performance. Consider the following modules

LaunchKernels[]
Compute[data_, 1] := Module[
{n1, n2},
{n1, n2} = Dimensions[data];
Table[Total[data[[i11]]*data[[i12]], Infinity],
{i11, n1}, {i12, n1}, {d, 1, n2}]
];
Compute[data_, 2] := Module[
{n1, n2},
{n1, n2} = Dimensions[data];
ParallelTable[
Total[data[[i11]]*data[[i12]], Infinity],
{i11, n1}, {i12, n1}, {d, 1, n2}]
];

Its not really important, what is computed, but the time performance discussed later after rerunning. As an example, just create data as a 2 by 10 matrix and check identical computations of the normal module Compute[data,1] and the parallelized Compute[data,2]

n1 = 2;
n2 = 10^1;
data = RandomInteger[{0, 10}, {n1, n2}];
Compute[data, 1] == Compute[data, 2]

(*True*)

First run: Now, just do some calculation time check for increasing the number of rows and columns and plot the results (y axis is computation time, x axis are number of columns, blue: one row, orange: two rows)

n1max = 2;
n2max = 10^1;
t = ConstantArray[, {n1max, n2max}];
Do[
tloc = {};
dataloc = RandomInteger[{0, 10}, {n1, n2}];
Do[
AppendTo[tloc, AbsoluteTiming[Compute[dataloc, i];][[1]]]
, {i, 2}
];
t[[n1, n2]] = tloc;
, {n1, n1max}
, {n2, n2max}
]
plot =
Table[
ListPlot[t[[;; , ;; , i]],
PlotRange -> {0, Max[t]},
PlotLabel -> "Compute " <> ToString[i],
Joined -> True,
PlotLegends -> Automatic],
{i, 2}] // TableForm

Rerun: now, rerun the test just several times (here just 10 times) and look at the last evaluated time performance of the module with ParallelTable, it is now an order of magnitude slower while the the module with the standard Table shows naturally no changes!

nrerun = 10;
Do[
t = ConstantArray[, {n1max, n2max}];
Do[
tloc = {};
dataloc = RandomInteger[{0, 10}, {n1, n2}];
Do[
AppendTo[tloc, AbsoluteTiming[Compute[dataloc, i];][[1]]]
, {i, 2}
];
t[[n1, n2]] = tloc;
, {n1, n1max}
, {n2, n2max}
]
, {rerun, nrerun}
]
plot =
Table[
ListPlot[t[[;; , ;; , i]],
PlotRange -> {0, Max[t]},
PlotLabel -> "Compute " <> ToString[i],
Joined -> True,
PlotLegends -> Automatic],
{i, 2}] // TableForm

If you keep rerunning or just doing more computations with the modules, the time performance keeps getting worse.

Question: Why does the performance of ParallelTable within a Module drop so horribly when the module is RERUN several times? Actually, I am not interested in parallel computing here, but on what is being blown up and causes the parallel computations to take longer when you rerun the module. I also used Block and the slow-downs disappear, but I dont understand why. Is it because of the generation of unique local variables in Module and its scoping? Do these variables get stored somewhere, need to be checked every run for creating unique new ones and cause slower computation somehow when combined with automatic parallel programs? If yes, then it is kind of weird, since modules without automatic programs seem to be ok, as in the example above.


text:
# Thread: Estimate oredr O(h)

1. ## Estimate oredr O(h)

Consider non-dimensional differential equation for the height at the highest point is given by
$$h(\mu)= \frac{1}{\mu}- \frac{1}{\mu^2} log_e(1+\mu)$$
$0<\mu<<1.$
Deduce an estimate to $O(\mu)$ for $h(\mu)$ and compare with $t_h(\mu)=1-\frac{\mu}{2}+...$
=> I really don't how to start this question. please help me.

2. ## Re: Estimate oredr O(h)

I would start with a Taylor's series expansion of $ln(1+ \mu)$.

3. ## Re: Estimate oredr O(h)

Originally Posted by HallsofIvy
I would start with a Taylor's series expansion of $ln(1+ \mu)$.
$\log_e(1+\mu) = \mu - \dfrac{\mu^2}{2} + \dfrac{\mu^3}{3} - \dfrac{\mu^4}{4}+\cdots$ and plug that in,
to get $\log_e(1+\mu) =\dfrac12- \dfrac\mu3+\dfrac{\mu^2}{4}+\cdots.$
now, comparing $\log_e(1+\mu)$ with $t_h(\mu)=1-\frac{\mu}{2}+\cdots$
what can I say?

4. ## Re: Estimate oredr O(h)

Originally Posted by grandy
Consider non-dimensional differential equation for the height at the highest point is given by
$$h(\mu)= \frac{1}{\mu}- \frac{1}{\mu^2} log_e(1+\mu)$$
$0<\mu<<1.$
Deduce an estimate to $O(\mu)$ for $h(\mu)$ and compare with $t_h(\mu)=1-\frac{\mu}{2}+...$
=> I really don't how to start this question. please help me.
well done................
Soran University


text:
# homomorphism :))

Printable View

• November 15th 2009, 10:34 PM
GTK X Hunter
homomorphism :))
Suppose $GL(n,\mathbb{R})$ is a multiplicative group of invertible matrix ( $n$x $n$). Let $\mathbb{R}$ be an additive group of real numbers. Given $g:GL(n,\mathbb{R})\rightarrow\mathbb{R}$ with $g(A)=tr(A)$.
Is $g$ homomorphism? If yes then prove it! (Rofl)
• November 16th 2009, 01:46 AM
Defunkt
You should really be able to solve these by yourself!

For g to be a homomorphism, we need that for every $A,B \in GL_n(\mathbb{R}), tr(A)tr(B) = tr(AB)$

I'll leave the rest for you.


text:
18-118 Jussi Behrndt, Pavel Exner, Markus Holzmann, Vladimir Lotoreichik
The Landau Hamiltonian with $\delta$-potentials supported on curves (686K, pdf) Dec 22, 18
Abstract , Paper (src), View paper (auto. generated pdf), Index of related papers

Abstract. The spectral properties of the singularly perturbed self-adjoint Landau Hamiltonian $A_lpha =(i abla + A)^2 + lpha\delta_\Sigma$ in $L^2(R^2)$ with a $\delta$-potential supported on a finite $C^{1,1}$-smooth curve $\Sigma$ are studied. Here $A = rac{1}{2} B (-x_2, x_1)^T$ is the vector potential, $B>0$ is the strength of the homogeneous magnetic field, and $lpha\in L^\infty(\Sigma)$ is a position-dependent real coefficient modeling the strength of the singular interaction on the curve $\Sigma$. After a general discussion of the qualitative spectral properties of $A_lpha$ and its resolvent, one of the main objectives in the present paper is a local spectral analysis of $A_lpha$ near the Landau levels $B(2q+1)$, $q\in N_0$. Under various conditions on $lpha$ it is shown that the perturbation smears the Landau levels into eigenvalue clusters, and the accumulation rate of the eigenvalues within these clusters is determined in terms of the capacity of the support of $lpha$. Furthermore, the use of Landau Hamiltonians with $\delta$-perturbations as model operators for more realistic quantum systems is justified by showing that $A_lpha$ can be approximated in the norm resolvent sense by a family of Landau Hamiltonians with suitably scaled regular potentials.

Files: 18-118.src( 18-118.comments , 18-118.keywords , magnetic32.pdf.mm )


text:
Iteratively solving a kind of Signorini transmission problem in a unbounded domain
ESAIM: Mathematical Modelling and Numerical Analysis - Modélisation Mathématique et Analyse Numérique, Volume 39 (2005) no. 4, p. 715-726

In this paper, we are concerned with a kind of Signorini transmission problem in a unbounded domain. A variational inequality is derived when discretizing this problem by coupled FEM-BEM. To solve such variational inequality, an iterative method, which can be viewed as a variant of the D-N alternative method, will be introduced. In the iterative method, the finite element part and the boundary element part can be solved independently. It will be shown that the convergence speed of this iteration is independent of the mesh size. Besides, a combination between this method and the steepest descent method is also discussed.

DOI : https://doi.org/10.1051/m2an:2005031
Classification:  65N30,  65R20,  73C50
Keywords: Signorini contact, FEM-BEM coupling, variational inequality, D-N alternation, convergence rate
@article{M2AN_2005__39_4_715_0,
author = {Hu, Qiya and Yu, Dehao},
title = {Iteratively solving a kind of Signorini transmission problem in a unbounded domain},
journal = {ESAIM: Mathematical Modelling and Numerical Analysis - Mod\'elisation Math\'ematique et Analyse Num\'erique},
publisher = {EDP-Sciences},
volume = {39},
number = {4},
year = {2005},
pages = {715-726},
doi = {10.1051/m2an:2005031},
zbl = {pre02213936},
mrnumber = {2165676},
language = {en},
url = {http://www.numdam.org/item/M2AN_2005__39_4_715_0}
}

Hu, Qiya; Yu, Dehao. Iteratively solving a kind of Signorini transmission problem in a unbounded domain. ESAIM: Mathematical Modelling and Numerical Analysis - Modélisation Mathématique et Analyse Numérique, Volume 39 (2005) no. 4, pp. 715-726. doi : 10.1051/m2an:2005031. http://www.numdam.org/item/M2AN_2005__39_4_715_0/

[1] C. Carstensen, Interface problem in holonomic elastoplasticity. Math. Methods Appl. Sci. 16 (1993) 819-835. | Zbl 0792.73017

[2] C. Carstensen and J. Gwinner, FEM and BEM coupling for a nonlinear transmission problem with Signorini contact. SIAM J. Numer. Anal. 34 (1997) 1845-1864. | Zbl 0896.65079

[3] C. Carstensen, M. Kuhn and U. Langer, Fast parallel solvers for symmetric boundary element domain decomposition equations. Numer. Math. 79 (1998) 321-347. | Zbl 0907.65119

[4] M. Costabel and E. Stephan, Coupling of finite and boundary element methods for an elastoplastic interface problem. SIAM J. Numer. Anal. 27 (1990) 1212-1226. | Zbl 0725.73090

[5] G. Gatica and G. Hsiao, On the coupled BEM and FEM for a nonlinear exterior Dirichlet problem in ${R}^{2}$. Numer. Math. 61(1992) 171-214. | Zbl 0741.65084

[6] R. Glowinski, Numerical methods for nonlinear variational problems. Springer-Verlag, New York (1984). | MR 737005 | Zbl 0536.65054

[7] R. Glowinski, G. Golub, G. Meurant and J. Periaux, Eds., Proc. of the the First international symposium on domain decomposition methods for PDEs. SIAM Philadelphia (1988). | MR 972509

[8] Q. Hu and D. Yu, A solution method for a certain interface problem in unbounded domains. Computing 67 (2001) 119-140. | Zbl 1109.65309

[9] N. Kikuchi and J. Oden, Contact problem in elasticity: a study of variational inequalities and finite element methods. SIAM, Philadelphia (1988). | MR 961258 | Zbl 0685.73002

[10] J. Lions and E. Magenes, Non-homogeneous boundary value problems and applications, Vol. I. Springer-Verlag (1972). | MR 350177 | Zbl 0223.35039

[11] P. Mund and E. Stephan, An adaptive two-level method for the coupling of nonlinear FEM-BEM equations, SIAM J. Numer. Anal. 36 (1999) 1001-1021. | Zbl 0938.65138

[12] J. Necas, Introduction to the theory of nonlinear elliptic equations. Teubner, Texte 52, Leipzig (1983). | MR 731261 | Zbl 0526.35003

[13] E. Polak, Computational methods in optimization. Academic Press, New York (1971). | MR 282511

[14] J. Schoberl, Solving the Signorini problem on the basis of domain decomposition techniques. Computing 60 (1998) 323-344. | Zbl 0915.73077

[15] E. Stephan, W. Wendland and G. Hsiao, On the integral equation method for the plane mixed boundary value problem of the Laplacian. Math. Methods Appl. Sci. 1 (1979) 265-321. | Zbl 0461.65082

[16] X. Tai and M. Espedal, Rate of convergence of some space decomposition methods for linear and nonlinear problems. SIAM J. Numer. Anal. 35 (1998) 1558-1570. | Zbl 0915.65063

[17] X. Tai and J. Xu, Global convergence of space correction methods for convex optimization problems. Math. Comp. 71 (2002) 105-122. | Zbl 0985.65065

[18] D. Yu, The relation between the Steklov-Poincare operator, the natural integral operator and Green functions. Chinese J. Numer. Math. Appl. 17 (1995) 95-106. | Zbl 0885.35027

[19] D. Yu, Discretization of non-overlapping domain decomposition method for unbounded domains and its convergence.Chinese J. Numer. Math. Appl. 18 (1996) 93-102. | Zbl 0928.65146

[20] D. Yu, Natural Boundary Integral Method and Its Applications. Science Press/Kluwer Academic Publishers, Beijing/New York (2002). | MR 1961132 | Zbl 1028.65129


text:
$A.$ $\left(-\infty,-\frac{1}{2}\right) \cup(2 \sqrt{2},+\infty)$ $B.$ $\left(-\infty,-\frac{1}{2}\right) \cup(0,2 \sqrt{2})$ $C.$ $(-\infty, 0) \cup(0,2 \sqrt{2})$ $D.$ $(-\infty, 0) \cup(2 \sqrt{2},+\infty)$

D