text:
# iOS screenshots of overlays

When presenting choices to a user, iOS has overlays with rounded corners. An example is the overlay that appears when you want to delete an image from the Photos app.

Officially, these have a few names, depending on their exact look and how they’re used. For modal interaction, there are alerts and modal views; for non-modal (and some modal) interaction, there are popovers. Regardless of the name and the underlying code, they have a similar look, and I often like to include screenshots of them in my posts. I’ve recently come up with a way to do this without leaving a cluttered background in the image.

Immediately after taking a screenshot, it’s easy to crop the image down to nearly the right size, but virtually impossible to crop it down to exactly the right size, because you can’t zoom in with the iOS-supplied cropping tools.

And even if you could crop precisely to the edges, the rectangular corners would still have wisps of background peeking out from beyond the rounded corners.

My solution is a two-step process:

1. Use Pixelmator to crop precisely to the edges. This is a “by hand” operation that I just haven’t figured out how to automate.
2. Use Shortcuts to mask out the rounded corners and, optionally, add a solid gray background. To me, white, or near-white overlays look better against the white background of the blog if they’re set against a darker background.

I typically do an approximate crop right after taking the screenshot, leaving me with something like this:

I then open the image in Pixelmator and crop it down to hit the edges precisely.

There is a technique to this. If you zoom in to a corner and then choose the crop tool, Pixelmator will zoom back out before allowing you to crop. This doesn’t hurt anything, but it means you wasted your time by zooming first.

So choose the crop tool and then zoom in to one of the corners. You will almost certainly need to pan during this process, which you must do with two fingers, as Pixelmator interprets all one-finger swipes while in crop mode as directions to move the crop handles. Once you get zoomed in to a corner, use one finger to align the crop with the sides of the rounded corner. This is relatively easy to do because the lines jump one pixel at a time at high zoom.

After cropping the first corner, you’re best bet is to tap the Apply button and then go back into crop mode to do the opposite corner. Every time I’ve tried to crop both corners in a single trip to crop mode, I’ve screwed up the crop while moving from one corner to the other. Inevitably, Pixelmator interprets one of my zoom or pan motions as a one-finger swipe and changes the crop.

Now we have our overlay cropped down to a precisely aligned rectangle, which I save back into the Photos app.

It’s time to run the Round Corners shortcut. This is a Share Sheet shortcut that acts on images. It asks the user first for the corner radius to use in the masking.

I set the default radius to 40 pixels because I’ve found that to work reasonably well for most overlays. The rounded corner mask that Shortcuts applies isn’t an exact match for the rounded corners used in overlays. I think that’s because Shortcuts uses a quarter circle for the rounding (hence the need for a radius) and iOS uses a squircle.

The shortcut then asks if a background should be applied. The answer you give determines whether you end up with this

or this

Here are the steps of the Round Corners shortcut:

I think the comments do a decent job of explaining what’s going on, but there are two tricks worth noting. First, I’m using Federico Viticci’s technique of embedding a base64-encoded version of the background image into the shortcut itself. It’s there in the Text step a little more than halfway down. Second, to save space, that background image is just a 1×1 pixel image. It gets resized to slightly larger than the target image (20 pixels larger in all four directions) before the overlay is done.

An obvious improvement would be to get rid of the hand cropping. The OpenCV library, which has bindings for Python, might be a way to grab just the needed portion of the image and would probably handle the masking, too. It works in iOS, but I think you have to be a real developer, not just a scripter, to use it there. I could probably get it running on my Mac or blog server if I dedicate the time to it.

# Drafts, Shortcuts, and blogging

For the past several months, almost all of my blog posts have been written on my iPad. My system for publishing the posts, though, was still Mac-based. It consisted of a set of scripts and Makefiles that would compile the Markdown source of the post into HTML and regenerate whatever new pages were needed to update the site. It did all this locally, on the Mac, and then ran rsync to upload the new and altered pages to the blog server. A good system for all those years I was writing posts on the Mac, but less good if I’m going to be writing mostly on the iPad.

To publish a post written on the iPad, I had to get the Markdown source file over to the Mac (Dropbox made this easy) and then I had two choices:

1. Leave my iPad, go to the Mac and run the publishing scripts. I almost never did this.

The second option, in which the Mac was basically an intermediary between the iPad and the server, seemed like a waste. So a couple of days ago I moved all the publishing scripts and Makefiles to the server, cutting out the middle man.

My publishing system is a melange of Python and PHP—Python because that’s what I prefer scripting in; PHP because this used to be a WordPress site and I have some custom PHP from those days that I don’t want to rewrite. A few Makefiles control the scripts to ensure that only the pages that need to be regenerated are. A system like this runs as easily on Linux as it does on the Mac, so I just had to add a library or two and change a few paths here and there to get everything working on the server. Then it was time to do some scripting on the iPad.

First, I needed to be able to upload a draft from Drafts to the server. I already had a two-step action for uploading a draft to Dropbox, so I was more than halfway there.

The source code for a post starts with a header that looks something like this:

Title: Drafts, Shortcuts, and blogging
Keywords: drafts shortcuts blogging
Summary: A change to how I blog means new Drafts actions that use Shortcuts.
Image: https://leancrew.com/all-this/images2018/20181215-Publish%20shortcut%20options.png
Date: 2018-12-15 12:10:23
Slug: drafts-shortcuts-and-blogging

The name for the Markdown source file and the folder into which it’s saved are determined by the year, the month, and the slug. The first step in my uploading action is this script:

javascript:
1:  // Set template tags for the path and filename
2:  // of a blog post.
3:
4:  var d = draft.content;
5:
6:  // Set up regexes for header info.
7:  var dateRE = /^Date: (\d\d\d\d)-(\d\d)-\d\d \d\d:\d\d:\d\d$/m; 8: var slugRE = /^Slug: (.+)$/m;
9:
10:  // Get the year and month and set the path.
11:  var date = d.match(dateRE);
12:  var year = date[1];
13:  var month = date[2];
14:  var path = '/path/to/blog/source/' + year + '/' + month + '/';
15:
16:  // Get the filename from the slug.
17:  slug = d.match(slugRE)[1];
18:
19:  // Set tags for use in other action steps.
20:  draft.setTemplateTag('source_path', path + slug + ".md");

This is almost identical to the earlier script, so I won’t describe it in full. The main differences are in Line 14, which defined the path on the server to the folder where the Markdown source files are kept, and Line 20, which defines the source_path template tag that will be used in the second step of the action.

Drafts1 has action steps for easily uploading to Dropbox, Google Drive, One Drive, Box, and WebDAV, but not for uploading via SFTP. I could install Dropbox for Linux on the server or maybe get WebDAV working on it, but I didn’t really want to install new stuff on the server just to be able to upload files. I could also switch to using Coda or some other editor on the iPad that handles SFTP, but I wanted to stick with Drafts. Because I already know how to upload files via SFTP in Shortcuts, I decided to use the Run Shortcut action step:

This step call the Upload Blog Source shortcut (which we’ll get to in a minute) and passes to it the source_path template tag that was defined above, a line of 10 carets, and then the full contents of the current draft. As you can probably guess, the line of carets is there to provide a distinct separator that the Upload Blog Source shortcut can parse.

Speaking of the Upload Blog Source shortcut, here it is:

The second step of the shortcut splits the input text, using ten carets as the separator. This creates a list. The next two steps take the first item of that list, which is the source_path followed by a newline, and strips the trailing whitespace. This output is available to later parts of the shortcut through a magic variable. By default, this magic variable would be named Replace Text, but because there is another Replace Text step in the shortcut, I renamed it sourcePath to avoid confusion. Unfortunately, this renaming is hidden when you take a screenshot of a shortcut, which could be its own source of confusion.

The next three steps return to the list of split items created in Step 2, pull out the last item from it, and strip the leading whitespace. This leaves us with the text of the draft.

Finally, the last step connects to the server and runs the cat command to redirect the standard input passed to the step (the Markdown source) to a file defined by sourcePath.

This is harder to explain than it is to do, but it would be easier if Drafts had a native action step for SFTP. I think I’ll put that bug in Greg Pierce’s ear.

OK, now I have an action that saves a draft to the server. I can use Prompt to log onto the server and run the make command that generates the necessary HTML and publishes the new pages. But wouldn’t it be nicer to just have an action that does that directly from Drafts. Of course it would. This is a single-step action that uses Run Shortcut:

Boy, that’s dull. Here’s the shortcut it runs:

My Makefile has several sections. By default, when make is run without an argument, it runs the sections needed to publish a new post. When given the up argument, it runs the sections needed to update an already-published post. Thats why there are two options to the Publish shortcut.

Many of you are thinking I could have written a shortcut just like this to log in and run make on my Mac, which would have saved me the trouble of moving all my publishing scripts to the server. You’re right, I could have. But I never did because the incentive wasn’t strong enough. It was only after I put the publishing system on the server—something I’ve been meaning to do for longer than I’ve had an iPad—and needed to solve other problems that I felt compelled to write the publishing shortcut. Motivation is funny.

The obvious drawback to setting things up this way is that I’ve now made it harder to blog from my Mac. But BBEdit knows SFTP, so it won’t be hard to teach it how to upload a file to right place. And there are any number of ways on a Mac to run a command on a remote server. I’ll fill those holes soon.

1. Which is, by the way, Time Magazine’s #3 app of 2018

# An unfortunate hole in my portable brain

This morning I got an email from one of my business partners. She’s out of town on a job and needed our FedEx number sent to another lab so they can ship some samples to us. No problem, I thought, I’m sure I have it on my phone. But no, that was one of those things I always meant to save on my phone but never got around to. My partner thought she had it on her phone, too.

Here are the things I have gotten around to saving to my phone:1

• Social security numbers for myself (which is kind of silly—I never need to look it up) and my family. This includes my mother and father, both of whom are now dead.
• Driver’s license numbers for myself and my family. Also photos of the front and back of my license.
• Make, model, year, license, and registration numbers for our cars. Also images of the registration documents.
• Bank account, routing, and other numbers and codes for personal and business accounts.
• My TSA Precheck code.
• The number, expiration date, and a photo of my passport.

Some of these may seem silly, but I’ve made use of almost all of them at one time or another. A couple of years ago, when my mom moved to a nursing home and I needed to close out certain services at her house, I learned that the phone service was still in my dad’s name. She’d never changed it when he died ten years earlier. So I used his SSN (along with my grandmother’s maiden name, which wasn’t saved to my phone but didn’t need to be) to impersonate him with the phone company and get the account closed. That was a little weird.

(I have since learned that friends my age commonly pretend to be their aging parents to deal with customer service reps. I am, however, the only one I know who pretended to be a dead parent.)

As I look through the list, I see that I still haven’t added things I’ve always meant to. In particular, apart from the FedEx number, I should be keeping the account numbers for various insurance policies.

Up until recently, I’ve had (or intended to have) all of this stuff in secure notes in 1Password. As part of my shift to a more iCloud-based system, I’ve copied them over to locked notes in the Notes app. There have been advantages and disadvantages to the change.

• Secure notes in iOS 1Password won’t accept images. When I wanted to add a photo to a secure note, I had to be at my Mac to do so. Given that all the photos I wanted to add—typically cards or documents scanned with Readdle’s Scanner Pro—came from my phone, this was annoying bit of back-and-forth. On the positive side, once the image was in the secure note, I could see it on my phone or iPad.
• Unlocking Notes on iOS can can have its own back-and-forth annoyance. Sometimes the app is perfectly happy to unlock after looking at my face or scanning my fingerprint. But sometimes, it wants me to enter the iCloud Keychain password I’ve associated with Notes. Which means I have to unlock the Keychain and select the password to fill into the text field. Often, the just-unlocked note still won’t show itself to me until I go back to the list of notes and select it again. I’m sure there’s some logic behind this, but I have no idea what it is.

1. And iPad and Macs, but it’s mostly when I’m out with just my phone that I need them.


text:
#### Archived

This topic is now archived and is closed to further replies.

# Poportional random numbers

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

## Recommended Posts

I was thinking of how to generate random characters in my game, and came up with a great way of doing it using proportional random numbers. The idea is this, if you have a stats that can have a value between 0 and 100 where 50 is the average value for that stat, then the majority of values for that stat should be around 50. However if you generate a random value between 0 and 100 then all values are equally likely and thus there is no average value. A proportional random number works by taking a base value and three random numbers to generate a value that is in proportion to the average value. First you generate a random number between 0 and 1, to generate a sign value, either –1 or 1. The you generate a range value by generating a random number between 0 and 14, If the random is: 0-4 = 0 5-8 = 10 9-11 = 20 12-13 = 30 14 = 40 Lastly a modifier value is generated between 0 and 10. So the final value for the stat is this: Stat value = base_value + ( sign * ( range_value + modifer_value ) ) In this way the stats value is still generated randomly but the distribution of values remains proportional to the average value. ----------------------------------------------------- "Fate and Destiny only give you the opportunity the rest you have to do on your own." Current Design project: Ambitions Slave

##### Share on other sites
you could also sum several random numbers to get a nice bell curve, where most of the results are likely to be near the average.

##### Share on other sites
Or you could just make a look-up table where a single random number is looked up in a pre-calculated curve, that''s adjusted to fit your game. But that would be too simple :-)

##### Share on other sites
quote:

you could also sum several random numbers to get a nice bell curve, where most of the results are likely to be near the average

But summing several random numbers doesn''t mean your going to get a value in proportion to the predefined average. Especailly if the average value is say 20 on a scale from from 1 to 100.

quote:

Or you could just make a look-up table where a single random number is looked up in a pre-calculated curve, that''s adjusted to fit your game. But that would be too simple :-)

A look up table? That has to be most extermly inefficent way to generate a porportional random number. Think about it if you want to make the full range of values available from 1 to 100 and have a built in curve you have to mutiple entries in the table for every value,in the end you are making a table with several thousand entries.

-----------------------------------------------------
"Fate and Destiny only give you the opportunity the rest you have to do on your own."
Current Design project: Ambitions Slave

##### Share on other sites
1'' If your game can reasonably average at 20 and have a max of 100, any character with 100 in that stat would be majorly overpowered. Or if the importance of the stat decreases exponentially, in the end the difference between even 90 and 100 will have no considerable meaning. Either way, such a situation would be bad design.

2'' Summing values to find averages on a bell curve can also be normalized to fit ANY scale. End of discussion for this one.

3'' Even if you have a table with several thousand entries (say... 100x100), know how much memory it takes up? 10k. Wow.

4'' Your technique would not apply to an average of 20 out of 100 values anyways.

##### Share on other sites
quote:
Original post by RuneLancer
1' If your game can reasonably average at 20 and have a max of 100, any character with 100 in that stat would be majorly overpowered. Or if the importance of the stat decreases exponentially, in the end the difference between even 90 and 100 will have no considerable meaning. Either way, such a situation would be bad design.

How would it be bad design? For instance in an rpg if the max level was 100, and the average npc level was 20. How is that bad design? If the average was 50 that would be bad design, since it would mean that most people where halfway between a wimp and the most powerful person alive. In a real life situation, you can think of it this way, there is rather large diffrence between an average persons stamina and that of olympic mararthon runner. In that case 20 might represent average stamina 100 the max stamina the human body can have and olympic marathon runner would probably be somewhere around 80 or above.

quote:

2' Summing values to find averages on a bell curve can also be normalized to fit ANY scale. End of discussion for this one.

Again this doesn't work well unless the average value lies in the middle of the scale.

quote:

3' Even if you have a table with several thousand entries (say... 100x100), know how much memory it takes up? 10k. Wow.

I don't know about you but filling 10,000 values into a table by hand would be a serious waste of time. I can think of far more productive ways to spend my time. And if you had algorithim to fill the table why use the table and not the algorithim?

quote:

4' Your technique would not apply to an average of 20 out of 100 values anyways.

Umm, yes it does. The sign value is optional, and By changing the base value and range, it will work on any scale and average.

-----------------------------------------------------
"Fate and Destiny only give you the opportunity the rest you have to do on your own."
Current Design project: Ambitions Slave

[edited by - TechnoGoth on May 9, 2004 9:14:43 PM]

##### Share on other sites
Why don't you use a shifted bell curve to generate values near some mean? For example, use this method as an utility function, and generate a number using newNumber = (meanValue + stdDeviation*nextGaussian()), then clamp it between your desired minimum and maximum values. If you clamp it this way, the mean doesn't have to be exactly halfway between the min and max (of course, it won't be the "real" mean if it's not exactly halfway between, but it should be very close).

[edited by - Matei on May 11, 2004 7:54:55 PM]

##### Share on other sites
quote:
if you have a stats that can have a value between 0 and 100 where 50 is the average value for that stat, then the majority of values for that stat should be around 50.

I can't tell from this if you're saying that the majority of random values will naturally be close to the mean, or if you simply want them to be (as in a normal distribution). For example, if you have a uniform distribution with min of 0 and max of 100, the mean is 50 but there won't be clustering around the mean anymore than any other point (on average) because they're uniformly distributed.

quote:
However if you generate a random value between 0 and 100 then all values are equally likely and thus there is no average value.

Not quite right, at least not according to the definition of the average of a random distribution. What you defined (equally likely alternatives) is the uniform distribution. The average of the uniform distribution is (max-min)/2 or in your case 50. What you really meant I think is that no one value is more likely than the others.

As far as generating random numbers goes, there are lots of fairly simple methods for generating complex distributions in real time. The simplest approach for your purposes would be the following:

PRECOMPUTATIONAL STEPS: For each possible value (0 to 100) assign a probability (use a reference or another program or just pick numbers that look good). Since 50 is your mean and you want it to be the most likely, assign it the largest probability. Likewise 0 and 100 will be farthest away. Next create a lookup table that associates each number with the cumulative probability up to and including the probability of that point (for all points up to and including the current point, sum the probabilities to get a total).

When you want to generate a random number with this distribution, generate a uniform(0,1) called U random number using rand() or something like it. Then look that number up in the table, selecting the entry that is the closest in cumulative probability with exeeding U's value.

To shift the distribution without recomputing everything, just generate your random number, then add whatever offset you want to it. To scale it, generate a random number with your approximately normal distribution like I showed above, call it D, then multiply it by the scaling factor s. Then use U random number to interpolate between D and D+s.

Maybe an example would help:

In this example I only show a few values because it would take too long to type 100 (since I'm on break):
Stat    Prob.--------------0        0.051        0.102        0.153        0.40   This is the most likely value.4        0.155        0.106        0.05

The cumulative probability table is given below (this is our look-up table):

Stat    Cum. Prob.------------------0         0.051         0.152         0.303         0.704         0.855         0.956         1.00

Now generate a random number with rand(); it will be a real number between 0 and 1. Say it comes up as 0.39768792

We look that up in the table and find that the Stat with the smallest Cum. Prob. that exceeds 0.39768792 is 3 (with a cum. prob. of 0.7), so the Stat we generated is 3.

This is how you generate the numbers without shifting or scaling.

Now if you want to shift them, suppose that you now want to generate Stats from 7 to 13 with a most likely value of 10, just generate the Stat like before (so it's still 3), then add 7 which is the offset New Stat = (New base - Old base + Old Stat)

Finally if you want to scale the range, suppose now instead of 0 to 6, stat's range from 0 to 24, we do the following:

First find the Stat (3 in this case). Then multiply it by the scale factor (in this case 4 since we're going from a range of 6 to 24). This gives us a Stat of 3x4 = 12. The problem is if we multiply every Stat in the table by 4 we get the following values:

0 4 8 12 16 20 24.

Clearly we want to be able to get 1 2 3 5 6 7 ... as well. So we use the rand() number to get that. Ours was 0.3976892. We use this to interpolate between the current Stat and the next highest scaled Stat. In our case the next highest one is 16. If you look at the original Cum. Prob. table, you'll notice that we first select 3 (12 scaled) at 0.3 cum. prob. and we first select 4 (16 scaled) at 0.7 cum. prob. So we take set up the following equation to interpolate between 12 and 16 using the probability:

(0.3976892-0.3)/(0.7-0.3) = (New Stat - 12)/(16-12)

Solving for New Stat, we get New Stat = 12+(0.3976892-0.3)(16-12)/(0.7-0.3)

Thus New Stat = 12.976892. Round however you like, but I would probably round that up to 13.

Of course realize that scaling like this results in a uniform distribution between the scaled points (between 0 4 8 12 ... in our example). If you want to get a perfect distribution for all scaled up points, you will probably want to go with a continous distribution and then just round up or down as desired.

For example, you could approximate the probability curve (say the bell curve) with interconnected line segments or even Bezier curves, and then generate random numbers according to that distribution. It's not that different from the discrete method I showed, but the math is slightly more complicated.

For more info on the subject, Google "Generating random variates." Also check out www.mathworld.com and look at various random distributions.

[edited by - bob_the_third on May 12, 2004 2:35:29 PM]

[edited by - bob_the_third on May 12, 2004 2:37:03 PM]

[edited by - bob_the_third on May 12, 2004 2:41:45 PM]

[edited by - bob_the_third on May 12, 2004 2:58:27 PM]

##### Share on other sites
Um, I''m not sure you need to make things all that complicated. I recently finished a program that generates numbers based on an inputted range and the only reason it was as complex as it was is because I allowed the user to define any number of plot points, not just the maximum and minimum.

In order to give an accurate reply, I''d have to know a little more about what you''re looking for, such as changes in variance, minimum & maximum values... So far all I have is: average = stat. The following is my attempt to work from there.

For symetrical distributions, I think it''s safe to say average = (max + min) / 2. Let''s look at some quick ways to handle this. Note that I''m borrowing heavily from tabletop rpg systems here.

Dice Totals
Assume you generate x random numbers from a to b. This makes the maximum x * a and the minimum x * b. Given the above:
average = (max + min) / 2
stat = (x*a + x*b)/2
stat = x(a+b)/2

This can be quickly adapted by fixing all but one of these terms. The most obvious being b, the maximum per "roll".
2*stat = x(a+b)
(a+b) = 2*stat/x
b = 2*stat/x - a
For a real easy way, set a to 0 and x to 2. This gives you a simple b = stat. Just add up two random values from 0 to stat. The result will average at the stat value, with a minimum of 0 and maximum of 2*stat.

You could also leave x free, but this is more problematic. After all, you can generate random fractions, but fractional repetitions is a bit harder. If you want to try it though, the formula is: x = 2*stat/(a+b). The up side is that more repetions makes the skill more reliable as it''s level increases, due to a more center-heavy probability curve.

Variance Sum
This is equivalent to "average give or take variance". Basically you start with the base value, the add one random number and subtract another. Given that both random numbers are between a and b...
max = base + b - a, min = base + a - b
average = (max + min) / 2
average = (base+b-a + base+a-b)/2
average = 2*base/2
average = base
This means all you have to do is let result = stat + random(b) - random(b). This gives you a constant amount of variance regardless of skill level.
Note that you can also do this with more than 2 randoms. So long as you subtract as many rolls as you add, this will balance out. If you want an odd number of rolls, you''ll have to use the following variant.

Assume the result equals the base, plus the sum of all random numbers (each of which with a range of a to b).
max = base + x*b, min = base + x*a
average = (max + min) / 2
average = (base+x*b + base+x*a) / 2

Let''s solve for the base:
2*average = 2*base + x*b + x*a
2*base = 2*average - x(a+b)
base = stat - x(a+b)/2
If x,a, and b are constant, then this really just comes down to result = stat - constant + rolls.

Triple-point mapping
This is the most complex i''m going to go into here. Only use this one if you''re looking to have a fixed range and variable average. These results are not symetrical and will distort the bell curve.
Assume we want all results between a and b with a shifting midpoint. First we need a number between 0 and 2. You can get this either through one random number, or the sum of multiple number. The number of repetitions will determine your basic probability distribution. Now let''s look at a little psuedo-code:

if(total > 1) // high result
result = stat + (b - stat)*(total - 1)
else result = a + (stat - a)*total // low result

Basically, you just took a 0 to 2 probability curve and mapped in onto an a to b range. The problem is the scale varies depending on whether the total is above or below the expected average.
Here''s a bit of proof that this makes the stat the average. For the total: average = (min + max)/2 = (0+2)/2 = 2/2 = 1. Let''s look at both equations at the average total.
high:
result = stat + (b - stat)*(total - 1)
result = stat + (b - stat)*(1 - 1)
result = stat + (b - stat)*0
result = stat
low:
result = a + (stat - a)*total
result = a + (stat - a)*1
result = a + stat - a
result = stat

Topic Analysis
Let''s assume your method would produce a symetric distribution, this tells us that average = (min+max)/2.
min = base + -(range_max + mod_max)
min = base - (40 + 10)
min = base - 50
max = base + +(range_max + mod_max)
max = base + (40 + 10)
max = base + 50
This looks a lot like the "variance sum" mentioned above, with a range of 0-50 per randomizer. Try result = stat + random(50) - random(50) and you should get roughly the same results, but smoother and more quickly. If the curve is a bit off, you can try adding in a few more rolls. Unless you''re really attached to that range-value table, the results should be a close enough match.

Summary
Getting your average to equal the stat isn''t that hard, all it takes is a little algebra in the design phase. If anything, this problem needs more definition before it can be answered. For once, I have to agree with Runelancer. You really can get pretty much any kind of distribution by just summing up some randoms and adjusting accordingly. If you want a few more ideas, just look into tabletop rpgs.

##### Share on other sites
I thought it was clear, but I might be best to restate it more clearly.

Predefined Values:
Min
Max
Mean

where:
min < mean < max

Goal:

To generate x random numbers where the distrubtion of values in x, from min to max is nonuniform. Where the number of values in x decreases proportionaly to the values distance from mean.

So if we where to generate 100 random values with the following predifined data.
Min = 1
Max = 100
Mean = 50

Then the distubtion would look something like this.

value | number of values
41-60 | 34
31-40, 61-70 | 27
21-30, 71-80 | 20
11-20, 81-90 | 13
1-10, 91-100 | 6

Does that clear up what I''m trying to acchomplish?

-----------------------------------------------------
"Fate and Destiny only give you the opportunity the rest you have to do on your own."
Current Design project: Ambitions Slave

• 10
• 17
• 9
• 13
• 41

format: plain


text:
## Physics for Scientists and Engineers: A Strategic Approach with Modern Physics (4th Edition)

(a) $F = 100~N$ (b) The power output at t = 2.0 s is 400 W The power output at t = 4.0 s is 800 W The power output at t = 6.0 s is 1200 W
(a) We can find the sprinter's acceleration. $x = \frac{1}{2}at^2$ $a = \frac{2x}{t^2}$ $a = \frac{(2)(50~m)}{(7.0~s)^2}$ $a = 2.0~m/s^2$ We can find the horizontal force $F$ acting on the sprinter. $F = ma$ $F = (50~kg)(2.0~m/s^2)$ $F = 100~N$ (b) We can find the speed at t = 2.0 s $v = a~t$ $v = (2.0~m/s^2)(2.0~s)$ $v = 4.0~m/s$ We can find the power at t = 2.0 s $P = F~v$ $P = (100~N)(4.0~m/s^)$ $P = 400~W$ The power output at t = 2.0 s is 400 W We can find the speed at t = 4.0 s $v = a~t$ $v = (2.0~m/s^2)(4.0~s)$ $v = 8.0~m/s$ We can find the power at t = 4.0 s $P = F~v$ $P = (100~N)(8.0~m/s^)$ $P = 800~W$ The power output at t = 4.0 s is 800 W We can find the speed at t = 6.0 s $v = a~t$ $v = (2.0~m/s^2)(6.0~s)$ $v = 12.0~m/s$ We can find the power at t = 6.0 s $P = F~v$ $P = (100~N)(12.0~m/s^)$ $P = 1200~W$ The power output at t = 6.0 s is 1200 W


text:
# Counterintuitive Properties of High Dimensional Space

Our geometric intuition developed in our three-dimensional world often fails us in higher dimensions. Many properties of even simple objects, such as higher dimensional analogs of cubes and spheres, are very counterintuitive. Below we discuss just a few of these properties in an attempt to convey some of the weirdness of high dimensional space.

You may be used to using the word “circle” in two dimensions and “sphere” in three dimensions. However, in higher dimensions we generally just use the word sphere, or $d$-sphere when the dimension of the sphere is not clear from context. With this terminology, a circle is also called a 1-sphere, for a 1-dimensional sphere. A standard sphere in three dimensions is called a 2-sphere, and so on. This sometimes causes confusion, because a $d$-sphere is usually thought of as existing in $(d+1)$-dimensional space. When we say $d$-sphere, the value of $d$ refers to the dimension of the sphere locally on the object, not the dimension in which it lives. Similarly we’ll often use the word cube for a square, a standard cube, and its higher dimensional analogues.

### Escaping Spheres

Consider a square with side length 1. At each corner of the square place a circle of radius 1/2, so that the circles cover the edges of the square. Then consider the circle centered at the center of the square that is just large enough to touch the circles at the corners of the square. In two dimensions it’s clear that the inner circle is entirely contained in the square.

We can do the same thing in three dimensions. At each corner of the unit cube place a sphere of radius 1/2, again covering the edges of the cube. The sphere centered at the center of the cube and tangent to spheres at the corners of the cube is shown in red in Figure 2. Again we see that, in three dimensions, the inner sphere is entirely contained in the cube.

To understand what happens in higher dimensions we need to compute the radius of the inner sphere in terms of the dimension. The radius of the inner sphere is equal to the length of the diagonal of the cube minus the radius of the spheres at the corners. See Figure 3. The latter value is always 1/2, regardless of the dimension. We can compute the length of the diagonal as

\begin{align*} d((\frac{1}{2}, \frac{1}{2}, \ldots, \frac{1}{2}), (1,1, \ldots, 1)) &= \sqrt{\sum_{i = 1}^{d} (1 - 1/2)^2}\\ &= \sqrt{d}/2 \end{align*}

Thus the radius of the inner sphere is $\sqrt{d}/2 - 1/2$. Notice that the radius of the inner sphere is increasing with the dimension!

In dimensions two and three, the sphere is strictly inside the cube, as we’ve seen in the figures above. However in four dimensions something very interesting happens. The radius of the inner sphere is exactly 1/2, which is just large enough for the inner sphere to touch the sides of the cube! In five dimensions, the radius of the inner sphere is $0.618034$, and the sphere starts poking outside of the cube! By ten dimensions, the radius is $1.08114$ and the sphere is poking very far outside of the cube!

### Volume in High Dimensions

The area of a circle $A(r) = \pi r^2$, where $r$ is the radius. Given the equation for the area of a circle, we can compute the volume of a sphere by considering cross sections of the sphere. That is, we intersect the sphere with a plane at some height $h$ above the center of the sphere.

The intersection between a sphere and a plane is a circle. If we look at the sphere from a side view, as shown in Figure 5, we see that the radius can be computed using the Pythagorean theorem ($a^2 + b^2 = c^2$). The radius of the circle is $\sqrt{r^2 - h^2}$.

Summing up the area of each cross section from the bottom of the sphere to the top of the sphere gives the volume

\begin{align*} V(r) &= \int_{-r}^{r} A(\sqrt{r^2 - h^2})\; dh\\ &= \int_{-r}^{r} \pi \sqrt{r^2 - h^2}^2 \; dh\\ &= \frac{4}{3}\pi r^3. \end{align*}

Now that we know the volume of the $2$-sphere, we can compute the volume of the $3$-sphere in a similar way. The only difference is where before we used the equation for the area of a circle, we instead use the equation for the volume of the $2$-sphere. The general formula for the volume of a $d$-sphere is approximately

$$\begin{equation*} \frac{\pi^{d/2}}{(d/2+1)!}r^d. \end{equation*}$$

(Approximately because the denominator should be the Gamma function, but that’s not important for understanding the intuition.)

Set $r = 1$ and consider the volume of the unit $d$-sphere as $d$ increases. The plot of the volume is shown in Figure 6.

The volume of the unit $d$-sphere goes to 0 as $d$ grows! A high dimensional unit sphere encloses almost no volume! The volume increases from dimensions one to five, but begins decreasing rapidly toward 0 after dimension six.

### More Accurate Pictures

Given the rather unexpected properties of high dimensional cubes and spheres, I hope that you’ll agree that the following are somewhat more accurate pictorial representations.

Notice that the corners of the cube are much further away from the center than are the sides. The $d$-sphere is drawn so that it contains almost no volume but still has radius 1. This image also suggests the next counterintuitive property of high dimensional spheres.

### Concentration of Measure

Suppose that you wanted to place a band around the equator of the unit sphere so that, say, 99% of the surface area of the sphere falls within that band. See Figure 8. How large do you think that band would have to be?

In two dimensions the width of the band needs to be pretty large, indeed nearly 2, to capture 99% of the perimeter of the unit circle. However as the dimension increases the width of the band needed to capture 99% of the surface area gets smaller. In very high dimensional space nearly all of the surface area of the sphere lies a very small distance away from the equator!

To provide some intuition consider the situation in two dimensions, as shown in Figure 10. For a point on the circle to be close to the equator, its $y$-coordinate must be small.

What happens to the values of the coordinates as the dimensions increases? Figure 11 is a plot of 20000 random points sampled uniformly from a $d$-sphere. As $d$ increases the values become more and more concentrated around 0.

Recall that every point on a $d$-sphere must satisfy the equation $x_1^2 + x_2^2 + \ldots x_{d+1}^2 = 1$. Intuitively as $d$ increases the number of terms in the sum increases, and each coordinate gets a smaller share of the single unit, on the average.

The really weird thing is that any choice of “equator” works! It must, since the sphere is, well, spherically symmetrical. We could have just as easily have chosen any of the options shown in Figure 12.

### Kissing Numbers

Consider a unit circle in the plane, shown in Figure 13 in red. The blue circle is said to kiss the red circle if it just barely touches the red circle. (Leave it to mathematicians to think that barely touching is a desirable property of a kiss.) The kissing number is the maximum number of non-overlapping blue circles that can simultaneously kiss the red circle.

In two dimensions it’s easy to see that the kissing number is 6. The entire proof is shown in Figure 14. The proof is by contradiction. Assume that more than six non-overlapping blue circles can simultaneously kiss the red circle. We draw the edges from the center of the red circle to the centers of the blue circles, as shown in Figure 14. The angles between these edges must sum to exactly $360^{\circ}$. Since there are more than six angles, at least one must be less than $60^{\circ}$. The resulting triangle, shown in Figure 14, is an isosceles triangle. The side opposite the angle that is less than $60^{\circ}$ must be strictly shorter than the other two sides, which are $2r$ in length. Thus the centers of the two circles must be closer than $2r$ and the circles must overlap, which is a contradiction.

It is more difficult to see that in three dimensions the kissing number is 12. Indeed this was famously disputed between Isaac Newton, who correctly thought the kissing number was 12, and David Gregory, who thought it was 13. (Never bet against Newton.) Looking at the optimal configuration, it’s easy to see why Gregory thought it might be possible to fit a 13th sphere in the space between the other 12. As the dimension increases there is suddenly even more space between neighboring spheres and the problem becomes even more difficult.

In fact, there are very few dimensions where we know the kissing number exactly. In most dimensions we only have an upper and lower bound on the kissing number, and these bounds can vary by as much as several thousand spheres!

Dimension Lower Bound Upper Bound
1 2 2
2 6 6
3 12 12
4 24 24
5 40 44
6 72 78
7 126 134
8 240 240
9 306 364
10 500 554
11 582 870
12 840 1357
13 1154 2069
14 1606 3183
15 2564 4866
16 4320 7355
17 5346 11072
18 7398 16572
19 10668 24812
20 17400 36764
21 27720 54584
22 49896 82340
23 93150 124416
24 196560 196560

As shown in the table, we only know the kissing number exactly in dimensions one through four, eight, and twenty-four. The eight and twenty-four dimensional cases follow from special lattice structures that are known to give optimal packings. In eight dimensions the kissing number is 240, given by the $E_{8}$ lattice. In twenty-four dimensions the kissing number is 196560, given by the Leech lattice. And not a single sphere more.

Tags:

Updated:


text:
# testarguments

#### 22-05-2021

Prediction algorithms typically have at least one user-specified argument that can have a considerable effect on predictive performance. Specifying these arguments can be a tedious task, particularly if there is an interaction between argument levels. This package is designed to neatly and automatically test and visualise the performance of a user-defined prediction algorithm over an arbitrary number of arguments. It includes functions for testing the predictive performance of an algorithm with respect to a set of user-defined diagnostics, visualising the results of these tests, and finding the optimal argument combinations for each diagnostic. The typical workflow involves:

1. Defining a prediction algorithm that uses training data and predicts over a testing set.
2. Defining a set of diagnostics as a function that quantify the performance of the predictions over the testing set.
3. Using test_arguments() to train and test the prediction algorithm over a range of argument values. This creates an object of class testargs, the central class definition of the package.
4. Visualising the predictive performance using plot_diagnostics().
5. Computing the optimal combination of arguments for each diagnostic using optimal_arguments().

## Example: Poisson regression with glm()

We demonstrate testarguments using a Poisson regression example, where the prediction algorithm is the generalised linear model (GLM) implemented with glm().

### Setup

First, load testarguments and simulate training and testing data. The data is Poisson distributed, with conditional expectation constructed by passing a fourth-order polynomial function of a covariate x through an exponential link function.

library("testarguments")
RNGversion("3.6.0"); set.seed(1)
n  <- 1000                                    # sample size
x  <- seq(-1, 1, length.out = n)              # covariates
Y  <- 3 + 2 * x * (x - 1) * (x + 1) * (x - 2) # linear predictor
mu <- exp(Y)                                  # mean of data
Z  <- rpois(n, mu)                            # simulate data
df       <- data.frame(x = x, Z = Z, mu = mu)
train_id <- sample(1:n, n/2, replace = FALSE)
df_train <- df[train_id, ]                    # training set
df_test  <- df[-train_id, ]                   # testing set

Next, we define a wrapper function that trains our prediction algorithm with df_train and predicts over df_test. In this example, the arguments that we wish to test are the link function, and the degree of the polynomial used to model the conditional expectation; these must be included as formal arguments in the wrapper function.

pred_fun <- function(df_train, df_test, degree, link) {

M <- glm(Z ~ poly(x, degree), data = df_train,

## Predict over df_test
pred <- as.data.frame(predict(M, df_test, type = "link", se.fit = TRUE))

## Compute response level predictions and 90% prediction interval
inv_link <- family(M)$linkinv fit_Y <- pred$fit
se_Y  <- pred\$se.fit
upr_Z = inv_link(fit_Y + 1.645 * se_Y),
lwr_Z = inv_link(fit_Y - 1.645 * se_Y))

return(pred)
}

Now, we define a diagnostic function, which should return a named vector. Here, we use the root-mean-squared error (RMSE), the mean-absolute error (MAE), and the coverage.

diagnostic_fun <- function(df) {
with(df, c(
RMSE     = sqrt(mean((Z - fit_Z)^2)),
MAE      = mean(abs(Z - fit_Z)),
coverage = mean(lwr_Z < mu & mu < upr_Z)
))
}

### Test the arguments of the prediction algorithm

Now we enter the main purpose of the package; to compute the user-defined diagnostics over a range of argument combinations. This is done using test_arguments(), which takes the prediction function, training data, testing data, the diagnostic fun, and a list of arguments to test. In this case, we will test the model using a polynomial of degree 1 to 6, and using the log and square-root link function.

testargs_object <- test_arguments(
pred_fun, df_train, df_test, diagnostic_fun,
arguments = list(degree = 1:6, link = c("log", "sqrt"))
)

### Visualise predictive performance

It is informative to visualise the predictive performance across all argument combinations; this is done using plot_diagnostics().

plot_diagnostics(testargs_object)

Using various aesthetics, plot_diagnostics() can visualise the performance of all combinations of up to 4 different arguments simultaneously. In the above plot, we can see that the predictive performance is not particularly sensitive to the choice of link function. We can focus on a subset of arguments using the argument focused_args. By default, this averages out the arguments not included in focused_args.

plot_diagnostics(testargs_object, focused_args = "degree")

### Optimal arguments

The function optimal_arguments() computes the optimal arguments from a testargs object. The measure of optimality is typically diagnostic dependent; for example, we typically wish to minimise the RMSE and run time, but we want coverage to be as close to the purported value as possible. Hence, optimal_arguments() allows one to set the optimality criterion individually for each diagonstic rule.

optimal_arguments(
testargs_object,
optimality_criterion = list(coverage = function(x) which.min(abs(x - 0.90)))
)
#>          degree link      RMSE       MAE coverage  Time
#> RMSE          4  log  5.559396  4.042814    1.000 0.003
#> MAE           4  log  5.559396  4.042814    1.000 0.003
#> coverage      6  log  5.586129  4.055873    0.862 0.003
#> Time          1 sqrt 16.070260 12.163413    0.020 0.002

In the output, the row names specify the diagnostic that is optimised by the corresponding combination of arguments. We can see that the RMSE and MAE are optimised when the degree of the polynomial function is 4 and the log link function is used; recall that these are the true values. In contrast, the coverage is optimised when the degree of the polynomial function is 6.


text:
# Align equations inside tabular

How can I align equations inside tabular? I want to place few lines of equation by side of the picture. But it turns out that I cannot use \& in order to shift equals signs to be one under another.

\documentclass{article}      % Specifies the document class

\usepackage{amsmath, amsfonts, mathtools, xfrac, empheq}
\usepackage{caption}

\begin{document}       % End of preamble and beginning of text.
\begin{tabular}{l r}
\begin{minipage}{0.6\textwidth}
\begin{align}
V^\pi = E_\pi \{ R_t \mid s_t = s \} \\
= E_\pi \left \{ \sum\limits_{k=0}^\infty \gamma^k r_{t+k+1} \mid s_t = s \right \}  \notag \\
= E_\pi \left \{ r_{t+1} + \gamma \sum_{k=0}^\infty \gamma^k r_{t+k+2} \mid s_t =s \right\} \notag
\end{align}
\end{minipage}
&
\begin{minipage}{0.4\textwidth}
%\includegraphics[width=\textwidth]{olcar_L11-8}
\captionof{figure}{Backup diagram}
\end{minipage}
\end{tabular}

\end{document}

I would like it to like this:

• You could put a {} around the minipage but simpler just remove the outer tabular which isn't doing anything very useful, just put the two minpages on a line separated by (say) \hfill (edit as written your line is overfull as your minipages add up to \linewidth but you have a paragraph indentation on the left and 4\tabcolsep from the padding added by the outer tabular. – David Carlisle Dec 4 '13 at 14:52

Overfull \hbox (39.00003pt too wide) in paragraph at lines 8--22

Due to paragraph indentation and 4 \tabcolsep (15+4*6=39pt).

If you simplify the markup, removing the tabular, the line fits the page, and you can use align with no problems:

\documentclass{article}      % Specifies the document class

\usepackage{amsmath, amsfonts, mathtools, xfrac, empheq}
\usepackage{caption}

\begin{document}       % End of preamble and beginning of text.

\noindent
\begin{minipage}{0.6\textwidth}
\begin{align}
V^\pi &= E_\pi \{ R_t \mid s_t = s \} \\
&= E_\pi \left \{ \sum\limits_{k=0}^\infty \gamma^k r_{t+k+1} \mid s_t = s \right \}  \notag \\
&= E_\pi \left \{ r_{t+1} + \gamma \sum_{k=0}^\infty \gamma^k r_{t+k+2} \mid s_t =s \right\} \notag
\end{align}
\end{minipage}\hfill
\begin{minipage}{0.4\textwidth}
%\includegraphics[width=\textwidth]{olcar_L11-8}
\captionof{figure}{Backup diagram}
\end{minipage}

\end{document}

If we use aligned instead of align, it is accepted inside tabular. I would suggest replacing \left and \right by a proper, smaller braces.

Edit, according to the request from the comment: Please observe, that aligned doesn't call math mode, hence such mode should be activated.

\documentclass{article}      % Specifies the document class

%\usepackage{amsmath, amsfonts, mathtools, xfrac, empheq}
\usepackage{amsmath, amsfonts, empheq}
\usepackage{caption}

\begin{document}       % End of preamble and beginning of text.
\begin{tabular}{l r}
\begin{minipage}{0.6\textwidth}
% PS %\begin{align} \begin{aligned} V^\pi &= E_\pi \{ R_t \mid s_t = s \} \\ &= E_\pi \left \{ \sum\limits_{k=0}^\infty \gamma^k r_{t+k+1} \mid s_t = s \right \} \notag \\ &= E_\pi \left \{ r_{t+1} + \gamma \sum_{k=0}^\infty \gamma^k r_{t+k+2} \mid s_t =s \right\} \notag %\end{align} \end{aligned}
\end{minipage}
&
\begin{minipage}{0.4\textwidth}
%\includegraphics[width=\textwidth]{olcar_L11-8}
\captionof{figure}{Backup diagram}
\end{minipage}
\end{tabular}

\end{document}

• Great answer. Only comment here is that aligned must be applied within a math environment. You have done this with \$ but it is not immediately obvious that the align is inside for anyone else who is looking. – twerdster Nov 29 '14 at 3:37


text:
# inequation with an integral

• May 16th 2009, 11:22 PM
gammafunction
inequation with an integral
Hi! Does anybody know how one can proof that $\frac{c}{1+c^2}\cdot exp(-\frac{c^2}{2}) \leq \int_c^\infty exp(-\frac{z^2}{2}) dz$ for $c>0$
I am thankful for any ideas.
• May 17th 2009, 02:13 AM
NonCommAlg
Quote:

Originally Posted by gammafunction

Hi! Does anybody know how one can proof that $\frac{c}{1+c^2}\cdot exp(-\frac{c^2}{2}) \leq \int_c^\infty exp(-\frac{z^2}{2}) dz$ for $c>0$
I am thankful for any ideas.

let $z=c\sqrt{2x+1}.$ then $I=\int_c^{\infty} \exp \left(\frac{-z^2}{2} \right) \ dz=c \exp \left(\frac{-c^2}{2} \right) \int_0^{\infty} \frac{e^{-c^2x}}{\sqrt{2x+1}} \ dx.$ but we know that $e^a \geq 1+a,$ for any $a \geq 0.$ thus $\frac{1}{\sqrt{2x+1}} \geq e^{-x}$ and hence:

$I \geq c \exp \left(\frac{-c^2}{2} \right) \int_0^{\infty} e^{-(1+c^2)x} \ dx=\frac{c}{1+c^2} \exp \left(\frac{-c^2}{2} \right).$

it was a little tricky, wasn't it? (Wink)
• May 17th 2009, 02:41 AM
gammafunction
Tricky and wonderful (Rofl). What a nice proof. Thank you a thousand times.


text:
In a class test, the sum of Shefali’s marks in Mathematics and English is 30. Had she got 2 marks more in Mathematics and 3 marks less in English, the product of their marks would have been 210. Find her marks in the two subjects.

Asked by Pragya Singh | 1 year ago |  100

##### Solution :-

Let us say, the marks of Shefali in Maths be x.

Then, the marks in English will be 30 – x.

As per the given question,

(x + 2)(30 – x – 3) = 210

(x + 2)(27 – x) = 210

⇒ -x2 + 25x + 54 = 210

⇒ x2 – 25x + 156 = 0

⇒ x2 – 12x – 13x + 156 = 0

⇒ x(x – 12) -13(x – 12) = 0

⇒ (x – 12)(x – 13) = 0

⇒ x = 12, 13

Therefore, if the marks in Maths are 12, then marks in English will be 30 – 12 = 18

and the marks in Maths are 13, then marks in English will be 30 – 13 = 17.

Answered by Abhisek | 1 year ago

### Related Questions

#### A natural number when increased by 12 equals 160 times its reciprocal. Find the number.

A natural number when increased by 12 equals 160 times its reciprocal. Find the number.

#### Find a natural number whose square diminished by 84 is equal to thrice of 8 more than the given number.

Find a natural number whose square diminished by 84 is equal to thrice of 8 more than the given number.

#### The numerator of a fraction is 3 less than the denominator. If 2 is added to both the numerator

The numerator of a fraction is 3 less than the denominator. If 2 is added to both the numerator and the denominator, then the sum of the new fraction and the original fraction is $$\dfrac{29}{20}$$ Find the original fraction.