Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,442 answers

573 users

How to calculate the mean and the standard deviation of an array of floating-point values in TypeScript

1 Answer

0 votes
function calculateMean(data: number[]): number {
    if (data.length === 0) return 0.0;

    let sum: number = 0.0;
    for (const value of data) {
        sum += value;
    }

    return sum / data.length;
}

function calculateStandardDeviation(data: number[], mean: number): number {
    if (data.length < 2) return 0.0;

    let sumOfSquaredDiffs: number = 0.0;
    for (const value of data) {
        const diff = value - mean;
        sumOfSquaredDiffs += diff * diff;
    }

    const variance: number = sumOfSquaredDiffs / (data.length - 1); 
    
    return Math.sqrt(variance);
}

const numbers: number[] = [3.4, 1.8, 4.3, 5.0, 6.2];
const mean: number = calculateMean(numbers);
const stddev: number = calculateStandardDeviation(numbers, mean);

console.log(`Mean: ${mean.toFixed(2)}`);
console.log(`Standard Deviation: ${stddev.toFixed(2)}`);
  
  
  
/*
run:
  
"Mean: 4.14" 
"Standard Deviation: 1.66" 
  
*/

 



answered Jun 29, 2025 by avibootz
...