Skip to content

Instantly share code, notes, and snippets.

@bencz
Last active December 28, 2015 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bencz/7522310 to your computer and use it in GitHub Desktop.
Save bencz/7522310 to your computer and use it in GitHub Desktop.
Calculate the SEN of X and COSSINE of X and, calculate PI
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace seno
{
static class Program
{
public static decimal Factorial(this int number)
{
return number == 0
? 1
: Enumerable.Range(1, number).Aggregate((i, j) => i * j);
}
public static IEnumerable<int> PrimeNumbers(int startRange, int count)
{
IEnumerable<int> range = Enumerable.Range(startRange, count);
return from n in range
let w = (int)Math.Sqrt(n)
where Enumerable.Range(2, w).All((i) => n % i > 0)
select n;
}
public static double ComputePI_linq(int num_steps)
{
return Enumerable.Range(0, num_steps).Aggregate(0d, (tot, next) => tot += Math.Pow(-1d, next) / (2 * next + 1) * 4);
}
static decimal ComputePI_Parallel(int num_steps)
{
decimal sum = 0.0M;
decimal step = 1.0M / (decimal)num_steps;
object monitor = new object();
Parallel.ForEach(Partitioner.Create(0, num_steps), () => 0.0M,
(range, state, local) =>
{
for (int i = range.Item1; i < range.Item2; i++)
{
decimal x = (i + 0.5M) * step;
local += 4.0M / (1.0M + x * x);
}
return local;
}, local => { lock (monitor) sum += local; });
return step * sum;
}
static void Time<t>(Func<t> work)
{
var sw = Stopwatch.StartNew();
var result = work();
Console.WriteLine(sw.Elapsed + ": " + result);
}
public static decimal Cos(decimal theta)
{
return Enumerable.Range(1, 10).Aggregate(
new { term = 1.0m, accum = 0.0m },
(state, n) => new
{
term = -state.term * theta * theta / (2 * n) / (2 * n - 1),
accum = state.accum + state.term
},
state => state.accum);
}
public static decimal Sin(decimal theta)
{
var nGrau = (Math.PI / 180);
var primes = PrimeNumbers(3, 15);
return primes.Select((item, index) =>
new { i = (index % 2) * 2 - 1, o = item })
.Aggregate(theta, (result, b) =>
result - b.i * ((decimal)Math.Pow(nGrau, (double)b.o) / Factorial(b.o)));
}
static void Main(string[] args)
{
Time(() => ComputePI_Parallel(1000000000));
Time(() => ComputePI_linq(1000000000));
var nGrau = (Math.PI / 180);
var nSeno = 5;
var theta = (decimal)(nGrau * nSeno);
var sin = Sin(theta);
var cos = Cos(theta);
var tg = 1 / (cos / sin);
Console.WriteLine("Seno: {0}", sin);
Console.WriteLine("Coss: {0}", cos);
Console.WriteLine("tang: {0}", tg);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment