Statistics Made Easier with STL

Statistics Made Easier with STL

rogrammers developing financial, scientific, and numerical analysis applications often need to reinvent the wheel, implementing statistical functions for calculate mean, median, percentiles, and similar statistical data. This solution will show you how to implement some of these operations with a few useful STL algorithms.


How can you implement statistical functions for calculating mean, median, and similar operations?


Use the algorithms defined in the and libraries.

Mean and Lean
The operations required for calculating the average of a range of elements consist of summing up all the values within that range and dividing the result by the number of elements. This task can become unduly complex when you have to deal with various types of ranges and looping through containers in order to accumulate their sum. However, using the right STL algorithms, it’s a cinch.

The first step consists of summing up all the values in a range. For this purpose, use the accumulate() algorithm defined in . This algorithm accumulates all elements within a range into a single value. accumulate() has three overloaded versions, but for the sake of brevity, the first version is used here, with the following prototype:

template T accumulate (InputIterator first,              InputIterator last,              T init);

The first two parameters mark the boundaries of the range. The third argument is an initial value that is added to the result. Usually, it’s 0 but under certain conditions, you may need to provide a different initial value.

Author’s Note: To avoid truncation and rounding problems, use the floating point datatype with the highest precision supported by your compiler?double or long double.

Suppose you have a container that stores students’ grades:

vector  grades;grades.push_back(89);grades.push_back(74);grades.push_back(89);grades.push_back(63);grades.push_back(100);

First, accumulate all the grades:

double res=accumulate(grades.begin(), grades.end(),0);

Next, calculate the average:

res=res/grades.size();

You can accomplish these two operations in one shot:

double res= accumulate(grades.begin(),grades.end(),0)/double(grades.size());cout<<"the average grade is: "<

The grades needn't be stored in a container object; you can apply accumulate() (as well as every other algorithm) and use a built-in array:

int grades[]={89, 74, 89, 63, 100};size_t range_size=sizeof(grades)/sizeof(grades[0]); double res= accumulate(grades, grades+range_size, 0)/double(range_size); 

Median
A median is the value that splits a range in two halves: half of the values are lower than or equal to the median value, and another half of the values is higher than the median. For example, in the range {60, 70, 89, 95, 100} the median is 89. It's easier to calculate the median when the range is sorted. If you're using a self-sorting container such as priority_queue or the associative containers map, multimap etc., you don't need to worry about sorting. If however the results are stored in a vector, simply call the sort() algorithm first:

sort(grades.begin(), grades.end());

Next, calculate the median like this:

cout<<*(grades.begin()+grades.size()/2); //89

If, for some reason, you prefer not to sort the container (for example, if you modify the container frequently), you can use the nth_element() algorithm instead. nth_element() ensures that the nth element in the container contains the value that would be stored in that position if the container were sorted. In addition, this algorithm ensures that all elements prior to the nth position would also precede that position in an ordered collection, and that all elements following the nth position would also follow that position in an ordered collection. However, nth_element() doesn't sort the container:

nth_element(grades.begin(),            grades.begin()+grades.size()/2,             grades.end());median=*(grades.begin()+grades.size()/2);

Median is a specific case of the 50th percentile. To find the element that is at a different percentile, say the 25th percentile, use the following nth_element() call. For the range 60, 70, 89, 95, 100, the result should be 70 because 25 percent of the elements in the given range are below this value:

nth_element(grades.begin(),            grades.begin()+int((grades.size()*0.25),             grades.end());int p_25=*(grades.begin()+int(grades.size()*.25)); cout<

Note that some compilers can't interpret the second argument of nth_element() without the explicit conversion to int.

Partitions
Sometimes you need to divide a range into two parts: all elements that satisfy a certain criterion, followed by all elements that don't. For example, to find out how many grades below 60 the range {20,30, 60,100} contains, use the partition() algorithm. partition() takes two iterators indicating the range's boundaries and a predicate. In this example, the predicate object is called smaller_than_sixty. partition() returns an iterator that is one past the end of the group of elements that satisfy this predicate:

for (vector::iterator it=grades.begin();     it < part;     it++){ cout<<*it<<" is smaller than 60"<

Without Deviating from the Standard
Although C++ doesn't have a statistics package, the and libraries contain many useful algorithms that significantly simplify the implementation of such a home-made library, as shown in this solution.

devx-admin

devx-admin

Share the Post:
Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

©2023 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.

Sitemap