Wednesday, March 21, 2018

LDSBR On-line Presenters




Topic: Writing process

Writing Accountability and Tracking Systems

Presenter: Katherine Cowley

Presentation:

One of the most difficult parts about creative writing is that you normally don’t have deadlines. Unless you have a book under contract, you don’t have a boss who is checking on how your writing is going and expecting a deliverable on a set date. In some ways, this is a good thing, but it can be easy to not achieve your writing goals if you don’t have accountability.
This presentation will address how to create writing accountability, first, through the creation of a habit-reward routine, and second, through using a tracking system, which can be low tech (a notebook) or a little more high tech (an app with time and project tracking). Ultimately, by using an accountability system, you can both write more and be happier with your progress.

About the presenter:

Katherine Cowley is an award-winning short story writer, who has been published in Segullah, the Mormon Lit Blitz, Steel and Bone, and Defenestration, to name a few. She was the guest editor for the 2016 Mormon Lit Blitz. She is a former English professor and radio producer, and lives with her husband and three children in Kalamazoo, Michigan. You can read many of her stories and learn more about her at katherinecowley.com.
Video Link:

-----------------
Books:
YA Fantasy:
Fall of the Dragon Prince, Forgotten Heirs Book 1 (Jolly Fish Press), Feb 2017
https://www.amazon.com/dp/B071RVZ3FP/ref=dp-kindle-redirect?_encoding=UTF8&btkr=1
Blade of Toran, Forgotten Heirs Book 2, Feb 2018
Arachnomancer, (Dragon Scales Publishing), Sept 2018
Middle Grade Fantasy:
Super Dungeon Explore: Dungeons of Arcadia (Future House Publishing), June 2018
Nonfiction:
Science in Fiction: Gravity, Nanotechnology and Relativity chapters, edited by Dan Kobolt (Writer's Digest) Fall 2018

www.authordanallen.com


resource links:

-------------- | | -------------



Topic: Writing to Market

How to Write to Market

Presenter: Victorine Lieske

Presentation:

Learn what it means to write to market, and how to do it, and the benefits of having an audience hungry for what you're writing.

About the presenter:

Victorine enjoys commercial success through her writing, thanks in part to her ability to analyze and adapt to the constantly changing trends in today's publishing environment. She self-published her first book, Not What She Seems, in April of 2010. In March of 2011, Not What She Seems began its 6 week run on The New York Times best selling eBook list. By May 2011 she had sold over 100,000 copies. Victorine's first romantic comedy novel hit the USA Today Best selling books list in January 2015.
Video Link: https://youtu.be/vOK4C03HNBE

-----------------
Books:
Too many to list now, but here's a link: https://www.amazon.com/Victorine-E.-Lieske/e/B003J4VTKO/ref=dp_byline_cont_ebooks_1


resource links:

-------------- | | -------------



Topic: Writing a Scene

Steaks and Stakes: Creating a scene with purpose and consequence.

Presenter: Ryan Decaria

Presentation:

In every scene, the focal character needs two things, a goal they are trying to accomplish (hmmm, steak) and consequences for failure (the stakes). In this class, we'll break down a scene and brainstorm how to improve the goals and stakes. Then we'll workshop scenes submitted by volunteers from the audience focusing on these two ideas.

About the presenter:

Ryan Decaria was raised on science fiction and fantasy novels and 80’s adventure movies. On rainy days, you can find him sulking on the window sill waiting for a treasure map, his future self, an alien buddy, and his own luck dragon. He lives in Northern Utah where he invents problems for invisible friends; he also writes fiction. Ryan approaches magic like a scientific field of study and science fiction as if were magic. Slam both together, and Mad Science is born, where anything is possible and it’s always a little gooey. His favorite parts are the monster always hiding in the closet, adventure around every corner, and a brilliant mind trying to set things right.
Video Link:

-----------------
Books:
Devil in the Microscope https://www.amazon.com/Devil-Microscope-Ryan-Decaria-ebook/dp/B07452YTPY


resource links:

-------------- | | -------------



Topic: Craft

Flash Editing

Presenter: Ali Cross

Presentation:

About the presenter:

Video Link:

-----------------
Books:


resource links:

-------------- | | -------------



Topic: Break and Q&A

Presenter: HOST

Presentation:

About the presenter:

Video Link: https://www.youtube.com/watch?v=5JjR1CTzh7U

-----------------
Books:


resource links:

-------------- | | -------------



Topic: General

Humor in Writing

Presenter: Shelly Brown

Presentation:

Learn techniques to bring humor and liveliness to your manuscript.

About the presenter:

Video Link:

-----------------
Books:
Ghostsitter
Mustaches for Maddie


resource links:

-------------- | | -------------



Topic: Short stories

Short Stories

Presenter: John M. Olsen

Presentation:

Learn about various types of short stories, markets for short stories, and going through the editing process.

About the presenter:

John M. Olsen reads and writes fantasy, science-fiction, steampunk, and horror as the mood strikes, and his short fiction is part of several anthologies. He devoured his father’s library in his teen years and has since inherited that formidable collection and merged it with his own growing library in order to pass a love of learning on to the next generation.
He loves to create things, whether writing novels or short stories or working in his secret lair equipped with dangerous power tools. In either case, he applies engineering principles and processes to the task at hand, often in unpredictable ways.
He lives near the Oquirrh Mountains in Utah with his lovely wife and a variable number of mostly grown children and a constantly changing subset of extended family.
Video Link: https://www.youtube.com/channel/UCnA8j86ivA4pQn5v_rcv_SA/live

-----------------
Books:
Novel:
Crystal King https://www.amazon.com/Crystal-King-Riland-Throne-Book-ebook/dp/B075B3Q7YN/

Some of my shorts in anthologies:
Protector of Newington (Storyhack Issue 1) https://www.amazon.com/StoryHack-Action-Adventure-Issue-1-ebook/dp/B075TVYBH2/
The Lure of Riches (Unbound, Clarion Call Volume 3) https://www.amazon.com/Unbound-Clarion-Call-Book-3-ebook/dp/B07832QFZ9/
Time to Think (Apocalypse Utah) https://www.amazon.com/Apocalypse-Utah-Collection-Horror-ebook/dp/B01ND005ZO/


resource links:

-------------- | | -------------



Topic: Story Structure

Structure: the creation of a story skeleton

Presenter: C. Michelle Jefferies

Presentation:

Learn how to create a base structure for your story. Whether you outline or pants it, this structure is for you. Giving you the freedom of both a direction to go and opportunity for the story and characters to change.

About the presenter:

C. Michelle Jefferies is a writer who believes that the way to examine our souls is to explore the deep and dark as well as the shallow. To manipulate words in a way that makes a person think and maybe even second guess. Her worlds include suspense, urban fantasy, and an occasional twist of steampunk. When she is not writing, she can be found on the yoga mat, hand binding journals, dyeing cloth, and serving ginger tea. The author and creator divides her time between stories, projects, and mothering four of her seven children on the wild and windy plains of Wyoming.
Video Link:

-----------------
Books:
Emergence Walnut Springs, https://www.amazon.com/Emergence-C-Michelle-Jefferies/dp/1599928728
Latent, Ascension, Interlude, Convergence, Catalyst, Story Structure and Master Chapter Outline Workbook Meraki Books.
https://cmichellejefferies.wordpress.com/bookstore/ . . . .
I was a “Writer of the Year” nominee for the League of Utah Writers for 2013 and 2014.
My short story “Broken” took third place in the 2008 short story contest for Life the Universe and Everything a SF/F symposium/writer’s conference.
My first chapter for ENCHANTED ETIQUETTE took third place in the LDStorymakers first chapter contest in 2012.
I won a song writing contest and had my song made into a video, also for the LDStorymakers conference in 2012.
I won a publishing contract with TM Publishing in 2012 for my manuscript ENCHANTED ETIQUETTE.


resource links:

-------------- | | -------------



Topic: Beta Reading

Speed "Beta"ing

Presenter: Jenny Rabe

Presentation:

Critiquing others and receiving and applying critique is a learned behavior. As writers we need it, strive for it, yearn for it. So how do we make the process easier? How do we find that niche of writers that knows our writing well, kicks our butt with a critique, but still inspires to stretch beyond what we think we’re capable? This class focuses on the art of beta-reading, critiquing others, and receiving that proverbial red pen without shutting down. After a small explanation of the art of beta-reading, the majority of the class will be a fun, hands-on application of supporting other writers in their writing through speed “beta”ing with multiple critique partners. Since this will be done online, whoever is online will be matched up with a partner and share a page or two of their writing, then they will be encouraged to have separate chats about their critiques. Each round will focus on a different skill. Looking at dialogue, theme, pacing, strong beginnings, etc. We probably will only have 2-3 rounds in that time...but enough to start a good conversation of what beta reading should be

About the presenter:

Jenny is an honest-to-goodness southern girl at heart. Other than her love for her husband, two boys, and her feline, writing, ballroom dancing, and public speaking are some of her favorite pastimes. She's an avid across-the-state traveler and spends her spare time running a beta-reading group online and serving her fellow authors.
Video Link:

-----------------
Books:
Playground Treasures https://www.amazon.com/Jenny-Flake-Rabe/e/B06XZQ28D2/ref=sr_ntt_srch_lnk_1?qid=1515474215&sr=8-1-fkmr0


resource links:

-------------- | | -------------



Topic: Live Q&A With Shadow Mountain Editor Lisa Mangum

Presenter: Lisa Mangum

Presentation:

Enjoy a conversation with Lisa Mangum, experienced editor and writer of fantastic and magical books.

About the presenter:

Lisa Mangum has loved and worked with books ever since elementary school, when she volunteered at the school library during recess. Her first paying job was shelving books at the Sandy Library. She worked for five years at Waldenbooks while she attended the University of Utah, graduating with honors with a degree in English. An avid reader of all genres, she has worked in the publishing department for Deseret Book since 1997. Besides books, Lisa loves movies, sunsets, spending time with her family, trips to Disneyland, and vanilla ice cream topped with fresh raspberries. She lives in Taylorsville with her husband, Tracy.
Video Link: https://www.youtube.com/watch?v=fLeqb4ZSEuE

-----------------
Books:
http://shadowmountain.com/author-book/lisa-mangum/


resource links:

-------------- For Lisa Only | https://hangouts.google.com/hangouts/_/3pxzisbm2ffknlmbbkgxbr33rme | -------------



Topic: ""

Presenter: Lisa Mangum

Presentation:

About the presenter:

Video Link: https://www.youtube.com/watch?v=fLeqb4ZSEuE

-----------------
Books:


resource links:

-------------- For Lisa Only | https://hangouts.google.com/hangouts/_/3pxzisbm2ffknlmbbkgxbr33rme | -------------



Topic: Craft/Dialogue

Who Said That? Crafting Character Development Through Dialogue

Presenter: Michelle Pennington

Presentation:

This class will cover the role that dialogue plays in character development, with particular emphasis on applying the concepts taught during the editing process.

About the presenter:

Michelle Pennington spends her days quoting movies with her husband and making messes faster than her four kids. She writes clean young adult, contemporary, fantasy, and regency romance. The genre might change, but her characters will always be falling in love.
She spends her spare time, what little there is, making designer sugar cookies, singing loud in church, and killing way too many house plants.

Michelle is an active contributor in the LDS and Clean Fiction writing communities. She is blessed to have the support of her family and amazing friends on this crazy journey, as well as the constant company of the characters who live in her imagination.
Video Link: PENDING

-----------------
Books:


resource links:

-------------- | | -------------



Topic: Unrealistic Storytelling Techniques

Satisfying Stories, Unrealistic Expectations

Presenter: Alana Howlett

Presentation:

Warning: Following the advice in this video may lead to reader dissatisfaction. Writer discretion is advised. This class talks about what factors play into reader expectations and how some of these expectations have become more malleable or rigid over time. Writers have been trained to reject some elements of realism over the value of the story--which, while the reader enjoys the story more, can also become detrimental to the reader's engagement with the real world. A writer might do well to attempt breaking writing conventions to see whether we are wrong about what the reader actually wants.

About the presenter:

Ali Cross is a USA TODAY bestselling author of science fiction and fantasy for both middle grade and young adult readers. She's long had a passion for passing her knowledge on to others which has afforded her many opportunities, including co-founding the world's first global online conference for independent authors.
Video Link: https://youtu.be/f2-YJ96KCMM

-----------------
Books:
Become (Desolation #1) 2013 Hollywood Book Festival Honorable Mention
2012 League of Utah Writers (Silver Quill) https://www.amazon.com/BECOME-Desolation-1-ebook/dp/B0064NRHMG/ref=pd_sim_kstore_4

Desolate (Desolation #2) https://www.amazon.com/gp/product/B008HJ2Z8Q/ref=series_rw_dp_sw

Destined (Desolation #3) https://www.amazon.com/gp/product/B00AM4HW82/ref=series_rw_dp_sw

Desolation Diaries (Desolation #3.5) https://www.amazon.com/Desolation-Diaries-Volumes-1-3-Cross-ebook/dp/B00J9YWPOM/ref=pd_sim_351_3?_encoding=UTF8&psc=1&refRID=9B26WY77NM6ARS5RT0FB

Blood Crown https://www.amazon.com/Blood-Crown-Ali-Cross-ebook/dp/B00IMGB8XM/ref=sr_1_1?ie=UTF8&qid=1393362073&sr=8-1&keywords=blood+crown+by+ali+cross

Frozen Souls https://www.amazon.com/Runes-Universe-Frozen-Kindle-Novella-ebook/dp/B06ZZWJ75T/ref=sr_1_1?s=digital-text&ie=UTF8&qid=1516080626&sr=1-1&keywords=frozen+souls+by+ali+cross

Jump Boys: SOS 2013 League of Utah Writers Silver Quill Winner https://www.amazon.com/Jump-Boys-Ali-Banks-Cross-ebook/dp/B00BFN2IHO/ref=sr_1_1?s=digital-text&ie=UTF8&qid=1516080751&sr=1-1&keywords=jump+boys%3A+sos

The Swift https://www.amazon.com/Swift-Ali-Banks-Cross-ebook/dp/B00KNYS762/ref=sr_1_1?s=digital-text&ie=UTF8&qid=1516080807&sr=1-1&keywords=the+swift+by+ali+banks+cross

Sigils and Spells: a Limited Edition Urban Fantasy Collection USA TODAY Bestselling title. (link currently unavailable due to Pronoun's closure)


resource links:

-------------- | | -------------



Topic: Writing/Professional Development

Wibbly-wobbly Timey-wimey: 8 Simple Strategies for Making Time to Write

Presenter: Bree Moore

Presentation:

Presentation of 8 strategies for finding and making time to write, focusing especially on those who have a job, are parents, etc. Includes: 1) Setting Goals 2) Getting Support (Friends, Family, etc.) 3) Get a Writing Buddy/Accountability 4) When you can't write, think about writing 5) Easy Access / Writing Tools 6) Develop your Skill 7) Finish SOMETHING 8) Embrace where you're at

About the presenter:

Bree Moore has been writing fantasy since the fourth grade. She lives in Ogden, is wife to an amazing husband, and the mother of four children. She writes fantasy novels between doling out cheerios and folding laundry.
"Woven" is Bree's first published novel, the start of what she intends to be an epic writing career.
In real-life, Bree works as a birth doula and midwife's assistant, attending women in pregnancy and labor, which is huge inspiration for her writing.
Video Link: https://youtu.be/Uyk5Mf6QnYo

-----------------
Books:
"Woven" by Bree Moore
https://www.amazon.com/Woven-Bree-Moore-ebook/dp/B073XVW3WQ
Whitney Awards Nominee


resource links: https://1drv.ms/b/s!Aorlo5cEOqCqhItnTKPhmCNC025hJA

-------------- | | -------------



Topic: Marketing books using social media

Connecting the Dots: Using Social Media to Create a Web of Content for Marketing Books

Presenter: Julie L. Spencer

Presentation:

What is social media? (Facebook, Google, Google+, Pinterest, Twitter, YouTube, Instagram, Goodreads, Snapchat, Tumblr, Amazon author page, website, blog, mailing list.)
Why use social media? (Connect with the world)
Which is the best social media platform to use? (depends on your genre)
What is the most important thing to do for long-term book marketing? (Get people on your email list)
Why can’t you just use groups, lists, hashtags, followers, subscribers, BookBub, etc. (They own your customers, they can change the rules anytime they want to, remember MySpace?)
What is the difference between content marketing and advertising? (with content marketing, you own the information, you created your content, most of the ‘cost’ is related to your time. With advertising, you are paying a person or company to get your message out. Either one is fine. You need to decide which avenue is right for you. Usually the answer is: use both)
Which social media platforms should you use? (all of them)
Which is the first platform you need (website, blog, email, email funnel to drive traffic from other social media sites to yours)
How do you drive their traffic to your website and ultimately to your email list? (smart URLs, links, bridges between the content you create on other social media sites back to yours)
Insider tips and tricks for each social media platform. What to do, what not to do, how to create a foundation on which to build.
Demonstrations for each of the main platforms and where to go to find more information for each platform. (this will have a module for each social media platform and could take awhile)
Affiliate marketing
How to think like Google (Search engine optimization, asking questions, smart titles and headings)
The words to use to make your content outshine your competition.
How to work with your competition to help both of you succeed more. (readers are voracious and no author can ever satisfy their readers. Find other writers like you and work together)
You must be in this for the long game. This is not a get rich quick scheme.
Where to find more information.

About the presenter:

Julie L. Spencer lives in the central Michigan area with her husband and teenage children. She has a very full life managing a conservation district office, writing grant proposals, newsletters, articles, and book reviews. Julie has been writing since she was in junior high, but prior to publishing her first novel, The Cove, her only published work was her master’s thesis. She loves to read and write New Adult Clean Contemporary fiction, is author of the Buxton Peak series, The Cove, The Man in the Yellow Jaguar, and has several more novels and non-fiction projects in the works.
Video Link:

-----------------
Books:
Buxton Peak: The Early Years
https://www.amazon.com/Buxton-Peak-Early-Contemporary-Novella-ebook/dp/B075CVVB4S/ref=asap_bc?ie=UTF8

Buxton Peak Book One: Who Is Ian Taylor?
https://www.amazon.com/Buxton-Peak-Book-One-Contemporary-ebook/dp/B01IQEB7Q2/ref=asap_bc?ie=UTF8

Buxton Peak Book Two: Center Stage
https://www.amazon.com/Buxton-Peak-Book-Two-Contemporary-ebook/dp/B01MQGJ02U/ref=asap_bc?ie=UTF8

Buxton Peak Book Three: The End of the Beginning
https://www.amazon.com/Buxton-Peak-Book-Three-Contemporary-ebook/dp/B06Y2PKX8Q/ref=asap_bc?ie=UTF8

The Cove
https://www.amazon.com/Cove-Adult-Clean-Contemporary-Novel-ebook/dp/B01IRB3UO6/ref=asap_bc?ie=UTF8

The Man in the Yellow Jaguar
https://www.amazon.com/Man-Yellow-Jaguar-Contemporary-Novella-ebook/dp/B075J8558J/ref=asap_bc?ie=UTF8

Buxton Peak: Silence from Nashville (featured in the Unspoken Words anthology)
https://www.amazon.com/Unspoken-Words-Romance-Compilation-Members-ebook/dp/B07628GV66/ref=asap_bc?ie=UTF8

The Phantom of the Chapel (featured in the Love Undefined anthology)
https://www.amazon.com/Love-Undefined-LDS-Beta-Readers-ebook/dp/B077XL1Z7P/ref=asap_bc?ie=UTF8


resource links:

-------------- | | -------------



Topic: Writing Craft

Adrenaline 101: Writing with Intensity

Presenter: Dan Allen

Presentation:

From the writing of blockbuster authors Orson Scott Card, Stephanie Meyer and James Patterson, learn the keys to writing with emotional intensity. From generating story momentum with backstory, foreshadowing, and character wants to creating tension with revelations in dialogue, this presentation teaches how to amplify the emotional response of readers to story action.

About the presenter:

After fifteen years in the lab designing lasers, nanoparticles and smart phone sensors, author Dan Allen roared onto the writing scene in 2017 with the fantasy epic Fall of the Dragon Prince. At home in the Rocky Mountains, Dan is CFO (chief fun officer) of his family and enjoys cosplay, escape rooms, game design, and general science mayhem. You can keep up with Dan’s latest fantasy and scifi on his website authordanallen.com and send him random science questions.
Video Link: https://www.youtube.com/watch?v=VkTmUMyUjBM

-----------------
Books:
YA Fantasy:
Fall of the Dragon Prince, Forgotten Heirs Book 1 (Jolly Fish Press), Feb 2017
https://www.amazon.com/dp/B071RVZ3FP/ref=dp-kindle-redirect?_encoding=UTF8&btkr=1
Blade of Toran, Forgotten Heirs Book 2, Feb 2018
Arachnomancer, (Dragon Scales Publishing), Sept 2018
Middle Grade Fantasy:
Super Dungeon Explore: Dungeons of Arcadia (Future House Publishing), June 2018
Nonfiction:
Science in Fiction: Gravity, Nanotechnology and Relativity chapters, edited by Dan Kobolt (Writer's Digest) Fall 2018

www.authordanallen.com


resource links:

-------------- | | -------------



Topic: CLOSING

Presenter: Host

Presentation:

About the presenter:

Video Link: https://www.youtube.com/watch?v=VR7iENhaBWw

-----------------
Books:


resource links:

-------------- | | -------------
********

Friday, March 2, 2018

Template for the LDSBR On-line Writing Conference Presentation Blog Posts

(Tentative version 2 -- see version 1 below.)

Thank you, presenters, for all your support!

We need blog posts to tell potential attendees about your presentation. Please use the template below to provide us with yours:

========== Copy from the line below here ... ==========


My Presentation Title

Presenter: My Name

My presentation blurb paragraph one.

My presentation blurb optional paragraph two.

A paragraph about me.

{The presentation video conference link will go here, TBD, do not fill in.}

My invitation for questions for Q&A session.
========== ... to the line above here. ==========

Then substitute your presentation's information and paste it into a file in LibreOffice, ABI Word, MSWord, or Google document format. (Tex, Markdown, etc., may also work, if you prefer those.) Then e-mail the file as an attachment to joel dot rees at somewhere dot tld

An example is shown below:



Scripture Examples of
Writing as Communication

Presenter: Joel Rees

Have you ever wondered whether a writer can get into the Celestial Kingdom? Joel Rees has studied the question at length from a scriptural standpoint, and feels that he has the answer.

With the information from this presentation, the next time you feel down because the creative juices just won't flow, and are fearing that maybe your decision to pursue writing is offensive to God, you will have scriptures at your fingertips to help you beat the arrows of the adversary back.
Joel Rees is an unpublished author of off-beat, sleep-inducing fantasies, residing somewhere between Japan and Mars, and a constant worry to his wife and children. His genre is random pick. You may know him as one of the former Contrarions of Slashdot.

Presentation video conference link:
https://www.youtube.com/watch?v=PN_MTQP71SY

I will open time for questions after the presentation. If you would like me to prepare for a specific question, you may contact me at joel dot rees at somewhere dot tld.



Plain text will also work, in which case you can use the following:

========== Copy from the line below here ... ==========
@form

@Presentation-Title:My Title

@Presenter-Name:
My Name

@Presentation-Blurb:
My blurb in paragraph form.

@Presenter-Bio:
A paragraph about me.

@Place holder for link to video conference: {TBD, do not fill in.}

@Request-for-pre-Q&A-questions:
My invitation for questions.

@end
========== ... to the line above here. ==========



=============================================


(Tentative version 1)

Thank you, presenters!

We need blog posts to tell potential attendees about your presentation. Please use the template below:

========== Copy from the line below here ... ==========
@form

@Presenter-Name:
My Name

@Presentation-Title:
My Title

@Presentation-Blurb:
My blurb in paragraph form.

@Presenter-Bio:
A paragraph about me.

@Place holder for link to video conference: {TBD, do not fill in.}

@Request-for-pre-Q&A-questions:
My invitation for questions.

@end
========== ... to the line above here. ==========

Then substitute your presentation's information and e-mail it to joel dot rees at somewhere dot tld as plain text in the mail body or in an attached file.

If you want special formatting, we can't make guarantees, but please use the example below as a template and send your presentation blog post in a file in LibreOffice, ABI Word, MSWord, or Google document format. (Tex, Markdown, etc., is also possible.) But contact me first, because some special formatting just won't work.

An example is shown below:





@form

@Presenter-Name:
Joel Rees

@Presentation-Title:
How to Use
Inane Social Theories,
Arcane Magic and Pseudo-technology,
and Obscured Pretend Real Settings
to Put Your Audience to Sleep

@Presentation-Blurb:
You always wanted to be known to your neighbors as the biggest bore in the world. With the information in this presentation, you can set your sights higher than ever. You can be know to the whole world as the biggest bore in the galaxy.

Insomniacs will praise your name! Pharmaceutical companies will despise and hate you!

@Presenter-Bio:
Joel Rees is an unpublished author of off-beat, sleep-inducing fantasies, residing somewhere between Japan and Mars, and a constant worry to his wife and children. His genre is random pick. You may know him as one of the former Contrarions of Slashdot.

@Place holder for link to video conference: {TBD, do not fill in.}

@Request-for-pre-Q&A-questions:
I will be happy to answer any questions about arcane subjects.

Please refrain from asking questions that matter.

@end



The above will be formatted programmatically something as follows:



How to Use
Inane Social Theories,
Arcane Magic and Pseudo-technology,
and Obscured Pretend Real Settings
to Put Your Audience to Sleep

Presenter: Joel Rees

You always wanted to be known to your neighbors as the biggest bore in the world. With the information in this presentation, you can set your sights higher than ever. You can be know to the whole world as the biggest bore in the galaxy.

Insomniacs will praise your name! Pharmaceutical companies will despise and hate you!

Joel Rees is an unpublished author of off-beat, sleep-inducing fantasies, residing somewhere between Japan and Mars, and a constant worry to his wife and children. His genre is random pick. You may know him as one of the former Contrarions of Slashdot.

Presentation video conference link:
https://www.youtube.com/watch?v=PN_MTQP71SY

I will be happy to answer any questions about arcane subjects.
Please refrain from asking questions that matter.



Tuesday, June 27, 2017

Looking at Memory Layout

The programming language C allows you to look at memory layout.

Why would you want to do this?

To get a look at how dangerous a stack crash or smash might be.

In the C run time environment, there is usually a region of memory for statically allocated variables, another for variables allocated through the library by calling malloc() and friends, and another for variables allocated dynamically on the stack. And, of course, there is a region for the runnable object code, can't forget that.

Early on, in the old world of sixteen-bit computing, the allocations often looked something like this:


0xFFFF
  stack (dynamic variables, stack frames, return pointers)
0xFxxx ← SP
  gap
  heap (malloc()ed variables, etc.)
  statically allocated variables
0xF000
  application code
0x8000
  operating system code, variables, etc.
0x0000


There were many variations, of course. An M6800 memory map might look something like this:


0xFFFF
  reset vectors
  I/O ports and monitor code
0xFC00
  operating system code
0x8000
  stack (dynamic variables, stack frames, return pointers)
0x8xxx ← SP
  gap
  heap (malloc()ed variables, etc.)
  statically allocated variables
0x8000
  application code
0x0080
  operating system variables
0x0000


Either way, the problem is easy to see. In this kind of a map, the stack grows downward, and the malloc()ed variables in heap fill memory upward. There is a convenience of sorts, in that an application can be designed to use more of one and less of the other.

But they share the same space.

If a user pushes an application beyond its design limits the two regions can overlap. Since physical memory doesn't magically multiply and increase when the two overlap, writing to one overwrites what is in the other.

Imagine a chalkboard. You and a friend are working on a math problem at the chalkboard. You're doing the math on the left, and your friend is writing down the results that you get on the right.

Things go okay, until the two of you have about 20 results, and she starts erasing your work so she can write down your results.

You're trying to cooperate, but you just don't have enough room.

And after she erases your work to right down your results, if you have to go back, you don't know where to go back to. Your work is gone.

Or, say, you erase the results she has been so kind as to write down for you, to continue your work. That's just as bad, because you still end up not knowing where you are and how to go back so you can move ahead.

Larger address space and more memory doesn't make the problem go away, just gives you more room before things go boom. (There is a way to mitigate these problems, which I will talk about in another blog post on CPU design.)

That's the basic reason you want to know about the layout of your memory.

Now, I'm not going to do all of your homework for you, but this little bit of code can get you started:



/* stkreveal.c
// A Q&D tool to structure of C runtime address space.
// by Joel Matthew Rees, Amagasaki, Japan, 28 June 2017.
// Copyright 2017 Joel Matthew Rees, claimed to the extent possible.
// This source is very much derivative of so many other sources
// that claiming copyright should be meaningless.
// But lawyers are known to quibble for money,
// so I assert all such copyright as I can.
// Permission to use:
// Author extends permission to use the source
// and the object it produces when compiled freely
// for any and all purposes except to assert intellectual property claims.
// Author makes no claims about the safety or reliability of the code.
// USE AT YOUR OWN RISK.
*/


#include <stdlib.h>
#include <limits.h>
#include <stdio.h>


/* #define AUTOBLOCKSIZE */

#if defined AUTOBLOCKSIZE
#  if INT_MAX > 0x7fff
#     define BLOCKSIZE 0x10000000L
#  else
#     define BLOCKSIZE 0x4000
#  endif
#else
#  define BLOCKSIZE 0x1000
#endif


void reportaddress( char * label, char * addr )
{
   printf( "%32s: %20p (%22lu)\n", label, addr, (unsigned long) addr );
}


char globalvariable[ BLOCKSIZE ];


int findandshow( int * argc, char * argv[] )
{
   char * mallocedblock = malloc( BLOCKSIZE );
   int flag = mallocedblock != NULL;

   reportaddress( "program parameters", (char *) argv );
   reportaddress( "main() parameters", (char *) argc );
   reportaddress( "findandshow() parameters", (char *) &argc );
   reportaddress( "mallocedblock", mallocedblock );
   reportaddress( "globalvariable", globalvariable );
   reportaddress( "reportaddress() function", (char *) reportaddress );
   if ( flag )
   {
      free( mallocedblock );
   }
   return flag;
}

int main( int argc, char * argv[] )
{
   return findandshow( &argc, argv ) ? EXIT_SUCCESS : EXIT_FAILURE;  
}



(If you copy and paste, remember to make sure the brackets and ampersands, etc., survived. I explain where to get a compiler in several places, here, for instance.)

On one of my computers, I get the following:


me@mycomputer:~/games$ cc -Wall -o stkreveal stkreveal.c
me@mycomputer:~/games$ ./stkreveal
              program parameters:       0x7ffc1411c938 (       140720645196088)
               main() parameters:       0x7ffc1411c84c (       140720645195852)
        findandshow() parameters:       0x7ffc1411c818 (       140720645195800)
                   mallocedblock:            0x24d3010 (              38613008)
                  globalvariable:             0x600b60 (               6294368)
        reportaddress() function:             0x40059c (               4195740)



The actual numbers change from run to run, because of something called memory randomization, that is used to slow down attackers who want to make use of this little game we are playing.

The remainder of this project is how to figure out what address is showing you what, where.

And to figure out how to protect yourself in a world where Intel doesn't protect you.

And you might be interested in the blog post that started this one, which is still in progress half done now. It will come in two three four parts:
  1. Explaining the currently published issues,
  2. outlining a better approach at addressed regions
  3. describing how CPU manufacturers could completely protect the return address stack,
  4. and describing my perfect ideal processor that probably shall never be.
[JMR201707011051:

Maybe it won't be giving away too many clues to mention a few useful tools if you are running a *nix workstation or something similar. Fellow blogspot denizen gallier2 reminded me on my main blog (#1 in the list of rants above) of the pmap utility. Reading the man page on that will point you to some other useful things, as well.

(mmap() and brk() may be of particular interest.)

To use pmap on a particular process, say an instance of bc or gforth or ruby, you would use ps to find out the process id:
ps wwaux | grep "gforth" $ ps wwaux | grep gforth
me       3281  0.0  0.1  22856  1412 pts/2    S+   11:00   0:00 gforth
me       3593  0.0  0.0   7412   884 pts/1    S+   11:01   0:00 grep gforth

The line of interest is the one in which the command is "gforth", not "grep gforth". If that output is confusing, you can use pgrep, to help figure out which is which:

$ pgrep -l gforth
3281 gforth
Now you know the process id, you can use pmap:
$ pmap 3281
3281:   gforth
0000000000400000    100K r-x--  /usr/bin/gforth-0.7.0
...
ffffffffff600000      4K r-x--    [ anon ]
 total            22860K
If you want to use pmap on the little program I showed you here, add a little wait-for-user-input loop at the end:




int main( int argc, char * argv[] )
{
   int ch = 0;
   int rval = findandshow( &argc, argv );
   while ( ( ( ch = fgetc( stdin ) ) != 'q' )
            && ( ch != EOF ) )
   {
      /* do nothing. */
   }
   return rval ? EXIT_SUCCESS : EXIT_FAILURE;  
}



 Typing 'q' and hitting enter will stop the program. While it's running, you can open another terminal window, find the process id with "pgrep stkreveal", and take a pmap of it.

Beyond that is your homework. Have fun.

But be careful with the knowledge you get from this sort of homework. Don't fall into the trap of thinking, "It's just a computer."

]


Tuesday, November 29, 2016

Using GMP to Approximate π

Okay, now I have
I guess I can now use the method as a way to show a little about how to use the Gnu Multi-Precision library.


The Gnu Multi-Precision library, GMP:

Here are
If your native language is not English, the wikipedia English wikipedia article has links to wikipedia articles in other languages. It's not much beyond an overview, but it should help a little, and those pages link some non-English resources.

Wish I had time to write this all in Japanese, or even to try to figure out how to annotate what I've written properly.

Once you get used to GMP, you'll probably find MPFR and MPC quite useful, as well. Probably in that order. (MPC builds new functionality onto MPFR which builds new functionality on GMP, if I read the docs correctly.) These add flexibility and methods of dealing with precision issues, and functions for complex numbers.

Note that GMP includes rational arithmetic -- explicit fractions!

Also note that the manual strongly suggests that, for what I'm doing here with multi-precision math, the MPFR library is more complete. If I were attempting a formal discussion of precision, yes, I would go with MPFR. But I'm not, and we need to start somewhere that's not too hard, so I'm starting with GMP.)



First, I converted the program I wrote using C's standard floating point math to the gmp libraries. The result is here:
https://osdn.net/users/reiisi/pastebin/4462

[JMR201705122219:

I should note that the program is not an efficient or fast way to calculate π. It's more of an easy demonstration of overly simplified use of multi-precision arithmetic. And, even there, I don't track the precision very carefully.

]

You can refer to my blog posts above for general explanations of what the program does. And comments in the source code should explain much of the differences between C's standard floating point math and the handling of GMP math, but I should probably add a few notes:

In the comments, I pretty much imply that mpf_t is a pointer. It isn't. Sorry. But having already pasted that into the paste buffer, I'll satisfy myself with an explanation here.

The type is a small structure containing a pointer, as is partially explained in the manual entry on memory management. Either way, you have to initialize it before you use it, as you see in the code. (You do have the code open in a text editor, or in another browser window, don't you?) 

C++ should (I think) allow using the multi-precision math almost the same as the standard floating point and integer types. I haven't tried, there may be some tricky stuff in loop syntax or such. I'm not a fan of C++, or of the idea of attempting to fold all program functionality onto existing syntax. This may have something to do with my coming from a FORTH background, where inventing new syntax on-the-fly doesn't interfere that much with the day-to-day workflow. (But it may create design nightmares down the road, and that's-a-different-story-sort-of.)

So using the GMP variables requires resigning yourself to C's function call syntax. But C makes that rather convenient, so it shouldn't be a problem, really.

The way they have set it up here, it requires the initialization to be separated from the declaration. Thus, all the variables of types provided by GMP that need to be accessible in the global scope of the main function are declared there at the top of the main function.

(I believe that C11 or somewhere says we should be able to declare them close to their first use, but I'm sticking with the most common idiom here.)

With all the globals declared, we are free to start ordinary procedural stuff, so the first thing I do is set the precision. The function call provided sets a precision that gives at least the number of bits of precision specified, including rounding. (MPFR allows you to be a little more precise so that you can control the loss of precision yourself.)
mpf_set_default_prec ( 67 )
ensures that we have at least 67 bits of precision. I want this to mimic (sort of) the default precision of bc when you call it as "bc -l" and load in the default math library.

You should want to know how I chose that 67 bits, so I'll tell you.

One binary digit (also called a "bit" -- binary digit) allows you to represent two numbers, usually interpreted as zero and one. That's not enough to represent decimal numbers.

Two bits give you zero to three, which is great for base four. Three bits give you zero to seven which is great for base eight, or octal. Four bits give you zero to fifteen, great for base sixteen, or hexadecimal.

So, if we wanted twenty digits of base sixteen precision, 20 ✕ 4 or eighty bits would be enough. (And we could set it at eighty without causing too many issues, really.)

Since you can also represent zero to nine in four bits, four bits is enough for one digit of binary coded decimal. And twenty binary coded decimal (BCD) would also take eighty bits.

But GMP is not doing BCD. It's doing binary math. Eighty bits of integer binary gives you the ability to represent from 0 to (280 - 1) That's
00000000000000000000000000000000000000000000000000000000000000000000000000000000 
to
11111111111111111111111111111111111111111111111111111111111111111111111111111111
That is easy to convert to hexadecimal. Each group of four binary 0s is one hexadecimal 0, and each group of four binary 1s is one hexadecimal "F". So, in hexadecimal, that's
0x00000000000000000000
to
0xFFFFFFFFFFFFFFFFFFFF
which probably doesn't look very meaningful to you, unless you play with this stuff for fun like I sometimes do. How can we convert that to decimal numbers that we feel comfortable with? Of course!
me@mymachine:~/games/piArea$ bc -l
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
10^20
100000000000000000000
2^80-1
1208925819614629174706175
so it's from 0 to 1,208,925,819,614,629,174,706,175 (using the US centric notation). So, if we plug in 20 digits of 9s and output that in binary, we can count the number of bits. Uggh. ;-)
obase=2
99999999999999999999
1010110101111000111010111100010110101100011000011111111111111111111
But, wait, there's a better way!

The common logarithm (log base 10, or log10) of a number is strongly related to the number of decimal digits that it takes to write:
log10(10000) == 4
The base two logarithm is strongly related to the number of binary digits it takes to write:

log2(16) == 4
If only bc could give us a way to calculate log10 and log2. :)

bc gives us the natural logarithm (ln) in the form of "l()"! And any logb is related to any other logc like this:
logb(x) = logc(x) / logc(b)
So, let's set the output base back to ten and define log2
obase=10
define l2(x) { return l(x)/l(2); }
l2(16)
4.00000000000000000002
l2(10^20)
66.43856189774724695808
If you're using a reasonably modern bc, you'll probably want to call the function "log2" instead of "l2", since "l2" looks like "12":
define log2(x) { return l(x)/l(2); }
l2(10^20)
66.43856189774724695808 
Having four tenths of a bit is kind of hard to do, so let's just say 67 instead of 66.4 bits, okay? And GMP gives us some extra bits and, by default, takes care of 4/5 rounding for us, which is a little more convenient here than what bc does. (We'll expect some difference in results at some point.)


Okay, now that the default precision is set, let's initialize all our variables. (We could have explicitly declared the precision on each initialization, but that would not have saved us the long explanation.)

We should note here that, if this program were more complex, especially if we were using GMP variables as local variables to functions other than main(), we would need to remember to clear them after use in order to avoid memory leaks. (I probably should have cleared them explicitly here to emphasize that.)

I avoid this allocation/deallocation problem here by declaring xsquared, ysquared, y, and deltaA in the outer block of main() rather than in the block local to the for loop, as I had in the native C code. (More on those, later.)

The initialize from string functions are really convenient:
mpf_init_set_str( mpf_t variable, char value[], int base )
so
mpf_init_set_str(deltaX, "0.025", 10);
initializes deltaX with 1/40 at 67 bits of precision (interpreting 0.025 as a base ten fraction).

When we have the value in one mpf_t variable, we can use that value directly in further initializations, as in
mpf_init_set( x, lastX );
And, if we really don't need to specify a value, just want to set the variables up for later use, we can do that, too:
mpf_init( deltaA );
These variables which I declared without initial values are the ones I'm using in the for loop, by the way.

If there are command line parameters (argc > 1), we have to convert the value for deltaX from the parameter. But the parameter is in a string, so that's straightforward:
mpf_set_str( deltaX, argv[ 1 ], 10 )
It's safer to be sure we got a good conversion when we are using unlimited precision, so I am checking the return value for indication of an error now. In the native C version, I figured there would be no harm in a bad conversion, but it probably would have been better to check.

Moving on to the interesting stuff, the for loop is not impacted as much as we might fear: 
for ( ; mpf_cmp( x, limit ) <= 0; mpf_add( x, x, deltaX ) )
The loop counter initialization here was completed explicitly when the variable was initialized, so I left it out of the loop. (It's just not a good idea to leave variables lying around declared but uninitialized. Unless you enjoy working with hidden bugs.)

The comparison expression
mpf_cmp( x, limit ) <= 0
is similar to saying
x <= limit
with standard C floating point types. mpf_cmp( a, b ) returns
  • an integer value less than zero (negative) if a is less than b, 
  • integer zero if a == b (something we should not expect or depend on),
  • and an integer greater than zero (positive) if a is greater than b.

Thus, the for loop continues until the value of x exceeds the limit.


The function call
mpf_add( x, x, deltaX )
is essentially the same thing as saying
x = x + deltaX
would be for standard C floating point types (except it does not yield the value assigned as a return value), thus, it means "increment x by deltaX".


The function parameters are listed in the order they would be written in our ordinary (modern infix) algebraic expressions, so, for each of add, mul (multiply), sub (subtract), and div (divide), the parameters are the same:
mpf_sub( mpf_t target, mpf_t left_op, mpf_t right_op )
Target gets the result, and the right op is added to, subtracted from, multiplied with, or divided into the left, as if it were written
target = left_op - right_op
in the case of mpf_sub, and the same with the rest. Again, an important difference is that these functions do not return a result, so we can't nest them and we have to deal with intermediate results ourselves.

Now you know why I have xsquared and deltaA as variables in the GMP version. We need some place to put the intermediate values. Thus
ysquared = 1.0 - ( x * x );
becomes
mpf_mul( xsquared, x, x );
mpf_ui_sub( ysquared, 1L, xsquared );
and
area += deltaX * y;
becomes
mpf_mul( deltaA, deltaX, y );
mpf_add( area, area, deltaA );
I'll repeat myself here -- I did not want xsquared, ysquared, y, and deltaA going out of scope in the loop, so I declared and initialized them in the outer block of main().

If I had a really good reason to keep them local to the loop block, I'd have needed to (re-)initialize them at the top of the loop and clear them at the bottom, to be sure the variables would be valid (and non-segment-faulting) and to keep memory from leaking. That takes enough extra time that I'd prefer to avoid it in a loop like this. And, of course, it gives more opportunity for bugs to creep in.

(In practice, I don't know of a compiler that would deliberately move loop local variables from iteration to iteration of a simple loop like this, but depending on that behavior is depending on something that is not promised in the standard. Not a good idea, and you'll forget to do it right in some places it really will matter.)

Finally, we can celebrate that the GMP provides us with a version of printf that handles gmp variables. Making your own output functions is fun, but sometimes you don't need that kind of fun.

And that's about it. Play with the code and have good kinds of fun!

(I may use this as an excuse to show some ways to parse command line parameters, but, if I do, it will be in another post.)

Friday, November 18, 2016

Using π to Check Your Floating Point Accuracy

In my post on using areas of rectangles to approximate π in C, I blithely asserted that standard C floating point math would lose accuracy compared to bc. But I didn't explain how I came to that conclusion.

I'll show you a little bit about how I got there, tiptoeing around some of the steps where it's easy to get lost.

First, refresh your memory about the bc program:
And here's how we'll call the program from the command line:
echo "q=1;m=32;scale=41;" | cat - halfpiArea_by_m.bc | bc -l
The name for the number of rectangles, "m" was rather awkward, but "q" for quiet should be easy to remember.

I suppose you may be wondering how that works.

First, echo just echoes what it is given into the standard output stream.

Second, the output stream of echo is piped to the standard input stream for cat and the command line tells cat to continue with the contents of the source code of the bc program. This way, cat concatenates things so that the result is a program that sets q, m, and scale appropriately before it begins:
q=1;m=32;scale=41;
/* ... */
if ( m < 1 ) { m = 11; }
s=0;
w = 1/m;
Unless we set them first, q, m, and d start at zero, and scale starts at 20 when we give bc the "-l" option.

So cat assembles the lines to set q, m, and scale with the program source and sends it all to the standard output stream.

Then the command line pipes the output of "cat" to "bc -l", and the program starts with scale, q, and m set to 41, 32, and 1.

Setting m changes the number of rectangles to divide the circle into, thus changing the width of the rectangles. We'll change that and examine the resulting attempt to calculate π.

The C program, halfpiArea, accepts a width as a parameter.

(That was not the best choice. You can change it if you want. I'm using the program as it is.)

The width is the inverse of the number of rectangles because the radius of the circle is 1. So we can calculate the width using bc:
echo "1/32" | bc -l
which tell us that one thirty-second is .03125000000000000000 (0.03125). We can select the decimal fraction that bc gives us on the terminal screen and copy it. In a Linux OS shell, we can usually use right-click after selecting the text. In a Mac OS X shell, the usual copy keyboard shortcut works.

In MSWindows, I think you will have to click the application icon in the left of the title bar and select "Edit" from the menu that pops up, then select "Copy" from the submenu. ;-*

Then we can run the C program by typing the program name and pasting the fraction in after as follows:
./halfpiArea .03125000000000000000
Except we want to run the bc program after the C program, so that we can get the output of both on the terminal screen at the same time:



Now we can select the output estimates for π and copy them to a text editor, where we can compare them at leisure.

We will notice that the two programs produce nearly the same results for counts of rectangles that are powers of two. Two rectangles, for example:
jwr@fun:~/work/mathgames/piArea$ ./halfpiArea .5
(             -0.5,0.866025403784439): 0.433012701892219
(                0,                1): 0.933012701892219
(              0.5,0.866025403784439):  1.36602540378444
(                1,                0):  1.36602540378444
Almost Pi:  2.73205080756888
jwr@fun:~/work/mathgames/piArea$ echo "q=1;m=2;scale=41;" | cat - halfpiArea_by_m.bc | bc -l
3: (1.00000000000000000000000000000000000000000, 0): 1.3660254037844\
3864676372317075293618347140
2.73205080756887729352744634150587236694280
These are the same, except for the last digit of the C program, which is actually correctly rounded, rather than just different:
2.73205080756888
2.73205080756887729352744634150587236694280
Similarly, 2048 rectangles:
jwr@fun:~/work/mathgames/piArea$ echo "1/2048" | bc -l
.00048828125000000000
jwr@fun:~/work/mathgames/piArea$ ./halfpiArea .00048828125000000000
(   -0.99951171875,0.0312461850698753): 1.52569263036501e-05
...
(                1,                0):  1.57078998270572
Almost Pi:  3.14157996541144
jwr@fun:~/work/mathgames/piArea$ echo "q=1;m=2048;scale=41;" | cat - halfpiArea_by_m.bc | bc -l
2049: (1.00000000000000000000000000000000000000000, 0): 1.5707899827\
0572260019288624147880158332158
3.14157996541144520038577248295760316664316
which are the same to the last digit of the C output:
3.14157996541144
3.14157996541144520038577248295760316664316
In fact, the C program is well behaved all the way to 216:
jwr@fun:~/work/mathgames/piArea$ echo "2^16" | bc -l
65536
jwr@fun:~/work/mathgames/piArea$ echo "1/(2^16)" | bc -l
.00001525878906250000
jwr@fun:~/work/mathgames/piArea$ ./halfpiArea .00001525878906250000
Almost Pi:  3.14159258349584
jwr@fun:~/work/mathgames/piArea$ echo "q=1;m=2^16;scale=41;" | cat - halfpiArea_by_m.bc | bc -l
65537: (1.00000000000000000000000000000000000000000, 0): 1.570796291\
74791608251698437807118686209362
3.14159258349583216503396875614237372418724
jwr@fun:~/work/mathgames/piArea$ echo "q=1;m=2^16;scale=81;" | cat - halfpiArea_by_m.bc | bc -l
65537: (1.0000000000000000000000000000000000000000000000000000000000\
00000000000000000000000, 0): 1.5707962917479160825169843780711868627\
48822128541338008872254934835925225596242002
3.141592583495832165033968756142373725497644257082676017744509869671\
850451192484004
(Going to scale=81 did take a minute or four. I should time it:
scale=81
a(1)*4
3.141592653589793238462643383279502884197169399375105820974944592307816406286208996
Okay, three minutes, forty seconds.)

Here are the estimates:

3.14159258349584
3.14159258349583216503396875614237372418724
3.141592583495832165033968756142373725497644257082676017744509869671850451192484004 
The C program produces the same as the bc program to the C program's second-to-the-last digit.

Note that the bc program is showing precision loss out in the 37th digit. Again, remember why, from the fly-in-the-pi post.

And, just as a reminder (in bc -l),
scale=81
a(1)*4
3.141592653589793238462643383279502884197169399375105820974944592307816406286208996
So, even with all this effort, we have only calculated π to the sixth digit past the decimal point, which is also expected, see the theory post.

That's not bad results, really, but if we don't choose the number of rectangles carefully, the C program output starts varying from the bc program quite quickly.

Ten, 100, and 1000 are good, but 10,000 is not. 11 is good, but 23 is not. Try a few, and see if you can guess what numbers work better and which work worse, and why.

Now, if our only purpose were to calculate π to six decimal digits, we'd be satisfied with using 216 for the count and be satisfied with standard C floating point math.

But, of course, that's not the real purpose.

What we are really talking about here is a way to get good solutions to equations involving integral calculus. (Was I being sneaky for not warning you in advance?)

So we do care about the differences, sometimes. We can't always select the convenient counts of rectangles to estimate with. Which is why I'm going to demonstrate using the Gnu Multi-Precision library real-soon-now.


Saturday, September 24, 2016

Calculating π (pi) in C

Maybe I need a better hobby.

Or maybe math really is this fun.

Okay, where this came from -- I gave my son a challenge, and he wrote a short program in perl to calculate π by the area of a circle.

So I wrote one in my favorite calculator, bc.

Now, its a nice program, and I can check the accuracy with bc itself, using the arctangent function. But bc is not as fast as C, and this old intel processor is not that fast, either.

And the program had a bug. Well, in my original explanation, I forgot to mention the problem of rounding. Bc always rounds down. Or, rather, it just drops fractional bits past the current scale This produced some notable effects, which are partially resolved in bc by doubling the scale.

Perhaps one reason bc is not as well known as it might be is that bc doesn't help you with rounding.

And it gives you scale instead of precision or accuracy.

So the limits of computers bite you pretty quick with bc, where other similar solutions help you ignore the limits -- sometimes until it's too late.

Which is part of the reason I'm writing this rant.

Anyway, I also wrote a nice little program for calculating π in standard C, using the language's ordinary math. It uses the same basic approach as I used in the bc version, except that the bc version I showed has a few more bells and whistles.

(I actually started with a very minimalistic version in bc, then wrote the C program and uploaded it to the pastebin linked above, then added the comments and extra features to the bc version before uploading it to a pastebin, if you are wondering why.)

So, if you want a full explanation of the method C source, look at my rants on the bc version (linked above) and the comments in the bc source. I'll limit my comments here to details of C programming and the standard C run-time environment, and issues of rounding and accuracy.

(Modifying the C source to do midpoint and so on is something I leave for you to play with.)

Here's the source of the standard C program, with extra comments:


/* Computing the value of pi by integrating the area of a (half of a) circle.
// by Joel Matthew Rees, 1 August 2013
// Copyright Joel Matthew Rees
//
// Fair use acknowledged.
//
// All rights to this expression of the method reserved.
//
// (Starting from scratch isn't that hard,
// and you'll like the results better.)
// -- Really, writing small programs like this from scratch
// is an excellent way to learn the basic grammar and runtime
// of a programming language. DIY!
// 
//
// Compile with the right libraries:
// cc -Wall -lm -o halfpiArea halfpiArea.c
//
// C language programs have to be compiled. You can't just run them.
// You have to save the source as halfpiArea.c
// and then run the compiler command above in a shell:
// http://joels-programming-fun.blogspot.com/2013/08/get-shell.html
//
// The compiler will catch simple errors in the source,
// and try to give you hints on how to fix them.
// Learning how to read the hints is a topic for another rant or more.
//
// If the compiler succeeds, the command line above will save
// the executable program in a file called halfpiArea,
// which you then run by typing 
// ./halfpiArea
// in the shell.
//
//
*/


/* The following lines help the compiler to figure out
// what functions you are using from the standard library
// and how you should be using them:
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* They literally include information about those functions
// into this program.
*/


/* The main function of a C program in a standard runtime environment
// is pretty much always called "main()".
// And it has two or three standard arguments.
// I only tell the program about two:
// argc is the integer count of the command line arguments,
// and argv[] is the array of command line arguments, as character strings.
// I'll tell you more about the command line arguments below.
*/
int main( int argc, char * argv[] )
{
   /* All the variables here are declared as
   // double length floating point.
   // Accuracy is usually more than 11 useful digits,
   // Exponent range is usually more than about 10^(+-235).
   // Simplify way too much,
   // you can write numbers from 1e-235 to 1e235,
   // and, if we get the math write,
   // we can guarantee at least 11 good digits for pi.
   //
   // (Actually, the math normally supported in modern C libraries
   // is IEEE 754, which would be 10^(+-308) and at least 15 good digits.
   // Check C Language Data Types and IEEE 754 on Wikipedia, stackexchange,
   // etc., for more information.
   //
   // If you want to know what your compiler gives,
   // #include <limits.h> and play with the math.)
   */
   double area = 0.0; /* Sum the area here. */
   double deltaX = 0.025; /* Width of the rectangles (by default 1/40). */
   double lastX = -1.0; /* Track the left side. */
   double x; /* The right side. */
   double almostPi; /* The approximation of pi. */
   /* You will notice that we declare the names and types
   // of the variables before we use them.
   // C also allows us to set the initial value as we declare them.
   */

   if ( argc > 1 ) /* Command line arguments? */
   {  deltaX = strtod( argv[ 1 ], NULL ); /* Assume it's a different width. */
   }
   /* This allows us to set a different width on the command line.
   // 1/11 would be 0.09090909090909090909 to twenty decimal places:
   // ./halfpiArea 0.09090909090909090909
   // 1/8 == 0.125, 1/10 == 0.1, 1/100 == 0.01, 1/200000 == 0.000005
   */

   /* Note that starting from the half delta converges at least one decimal digit faster.
   // (That's because the height of the rectangle crosses the circle at midpoint,
   // rather than left edge or right. Draw the pictures to see why.
   // This is right edge, but changing to midpoint or left edge is trivial.)
   */
   for ( x = -1.0 + deltaX; x <= 1.0; x += deltaX )
   {
      double ysquared = 1.0 - ( x * x );
      double y = sqrt( ysquared );
      /* deltaX = x - lastX; Reminder for humans, only! */
      lastX = x;
      area += deltaX * y;
      /* Suppress long listings of the areas.*/
      if ( deltaX > 0.00005 ) /* 1/20000 */
      {  printf( "(%17.15g,%17.15g): %17.15g\n", x, y, area );
         /* %17.15g is a floating point field
         // of 17 digits with 15 digits to the right of the decimal.
         */
      }
   }

   almostPi = area * 2;
   printf( "Almost Pi: %17.15g\n", almostPi );
   return EXIT_SUCCESS;
}



Calculating π to eleven digits works okay with C doubles. But if you look at the listing of the areas, you see some odd differences, because C always rounds but bc always does as many exact digits as you tell it to with the scale variable.

Play with different widths, compare to the bc version, and see what you can learn.

(Modern C, from about C99, allows you to declare floating point types that use alternative rounding.)

And you should notice that C is very fast when compared to bc.

When you want to check the real value of π, remember:
echo "scale=41; a(1)*4;" | bc -l
from the shell command line, or
scale=41
a(1)*4
in bc, adjust scale to one more than the number of good digits you want.

And don't try 
./halfpiArea 0.0000000000000000000000000000000000000001
unless you really want to watch your computer contemplate its navel until you give up and shut it down. Start with
./halfpiArea 0.00001
and work your way up to 0.0000001 or so, where you get really noticeable waits.

And see if you can figure out whether midpoint is really better than right side, as I said it would be, when you start using widths smaller than 1/100 or so.

Oh. And play with the source code a bit, too.

[JMR201611182140:
I decided to post a few hints about playing with the programs:
http://joels-programming-fun.blogspot.com/2016/11/using-to-check-your-floating-point.html.  
]


[JMR201611292224:
Hopefully, I'll get a chance to post sample source with the GMP gnu multi-precision library "real soon now". (I've got one running, it just seems to take more time to write the rant than the source code.)
Here it is, demonstrating the principle with GMP:
http://joels-programming-fun.blogspot.com/2016/11/using-gmp-to-approximate-pi.html.
]

Wednesday, March 9, 2016

What is Spaghetti Code?

When I posted the rant on my political blog about the body of US law loking too much like spaghetti code, I borrowed some examples from the Wikipedia article on spaghetti code.

Then I tried to find a basic interpreter that would run those archaic examples.

:)

Setting up an environment to run this kind of archaic code is a bit beyond an introductory topic.

So, to keep the original rant from getting too cluttered, I'm posting some more modern code for those examples in this post.

First, the example that was called structured on Wikipedia:



110 FOR i = 1 TO 10
120     PRINT i; " squared = "; i * i
130 NEXT i
140 PRINT "Program Completed."
150 END 


All you need to do to get this running in a more modern BASIC is remove the line numbers and maybe spread the print statement out:



FOR i = 1 TO 10
    PRINT i;
    PRINT " squared = ";
    PRINT i * i
NEXT i
PRINT "Program Completed."
END 


Then the example that was called spaghetti, but I think isn't really:



10 i = 0
20 i = i + 1
30 PRINT i; " squared = "; i * i
40 IF i >= 10 THEN GOTO 60
50 GOTO 20
60 PRINT "Program Completed."
70 END


You'll need some labels, which is probably why they called it spaghetti. Here's how it might look for a more modern BASIC:



i = 0
L20:
i = i + 1
PRINT i;
PRINT  " squared = ";
PRINT i * i
IF i >= 10 THEN GOTO L60
GOTO L20
L60:
PRINT "Program Completed.";
END


And my example of simple spaghetti:


200 e = 0
210 GOTO 300
220 PRINT i; " squared = "; i * i
230 GOTO 300
260 REMARK Remember to set e before you start! 
300 ON e GOTO 310,330
310 i = 0 
320 e = 1 
330 IF i < 10 THEN i = i + 1 ELSE GOTO 350
340 GOTO 220
350 PRINT "Program Completed."
360 END 


This can be a little trickier, because many BASIC interpreters differ about how the support the IF/THEN/ELSE constructs. Not to mention whether they support the computed GOTO. The following should run in a modern interpreter:



e = 0
GOTO L300
L220:
PRINT i;
PRINT " squared = ";
PRINT i * i
GOTO L300
REM Remember to set e before you start! 
L300:
IF e = 0 THEN GOTO L310
GOTO L330
L310:
i = 0 
e = 1 
L330:
IF i >= 10 THEN GOTO L350
i = i + 1 
GOTO L220
L350:
PRINT "Program Completed."
END 


I used Basic256 as my more modern interpreter rather than Gambas3 because using labels in Gambas3 just feels funny. Also, I would have had to talk about setting up an environment for the code to run in.

Gambas3 is actually useful for production code, where Basic256 is more for helping people learn BASIC programming skills (which is why Basic256 already has the environment set up).

Just for amusement, here's how these would look in C --

The clean version:



#include <stdio.h>
#include <stdlib.h>

/* Print the first ten squares the simplest way possible:
*/


int main( int argct, char * argvar[] )
{
   int i;

   for ( i = 1; i <= 10; i = i + 1 )
   {
      printf( "%d squared = %d\n", i, i * i );
   }
   puts( "Program Completed." );
   return EXIT_SUCCESS;
}


A version using GOTOs:



#include <stdio.h>
#include <stdlib.h>

/* Print the first ten squares the simplest way possible:
*/


int main( int argct, char * argvar[] )
{
   int i;

   i = 0;
l20:
   i = i + 1;
   printf( "%d squared = %d\n", i, i * i );
   if ( i >= 10 )
      goto l60;
   goto l20;
l60:
   puts( "Program Completed." );
   return EXIT_SUCCESS;
}


The spaghetti-fied version:



#include <stdio.h>
#include <stdlib.h>

/* Print the first ten squares the simplest way possible:
*/


int main( int argct, char * argvar[] )
{
   int e, i;

   e = 0;
   goto l300;
l220:
   printf( "%d squared = %d\n", i, i * i );
   goto l300;
   /* Remember to set e before you start! */
l300:
   if ( e == 0 )
      goto l310;
   goto l330;
l310: 
   i = 0; 
   e = 1; 
l330:
   if ( i >= 10 )
      goto l350;
   i = i + 1; 
   goto l220;
l350:
   puts( "Program Completed." );
   return EXIT_SUCCESS;
}


Here's what a session compiling the code and running it should look like --



me@mybox:~/work/spaghetti$ cc -Wall -o spaghetti spaghetti.c
me@mybox:~/work/spaghetti$ ./spaghetti
1 squared = 1
2 squared = 4
3 squared = 9
4 squared = 16
5 squared = 25
6 squared = 36
7 squared = 49
8 squared = 64
9 squared = 81
10 squared = 100
Program Completed.



The amusing thing about the C source code is that even the worst example here will compile and run correctly on any standard C compiler. But you can tell which version will be easier to figure out and add features to in the future.

Just for a certain kind of completeness, here's a FORTH version of the same function:



: tensquares 
   cr
   11 1 do 
       i . ." squared = " i i * . cr
   loop ;



Which you would invoke by entering tensquares at the FORTH command line, giving the same output as above.

Doing a version with the FORTH equivalent of GOTOs would be even more of a time waster than the rest of this rant, so I won't bother. It's probably even less interesting.