I can't write a complex equation in code - c#

I have been trying to turn this one conplex equation into code and it appears that I might have done something wrong. Here's the image of the equation:
Here's is the first code I tried using to convert the equation into code.
double answer = 1 - (Math.Pow(f, n) * ((s * l / f) + Math.Pow((20 / f), w) / Math.Pow(20, n)));
Here is the code that I used in my second attempt:
double answer = 1 - Math.Pow(f, n) * ((s * l) / f) + Math.Pow((20 / f), w) / Math.Pow(20, n);
If I assume that every variable of the equation is 2, than I get -.02. But when I ran the code, the first attempt code returned a value of -8, while the second attempt returned -6.75.
Is there anything I'm doing wrong in my code right now? And also sorry if I'm bad at explaining stuffs.

I tested this out and got the result of -0.02. Try splitting up the code to make it more legible. It might help you diagnose the syntax of your complex equation on one line.
double f = 2;
double n = 2;
double s = 2;
double w = 2;
double l = 2;
double A = Math.Pow(f, n);
double B = (s * l) / f;
double C = Math.Pow((20 / f), w);
double bottom = Math.Pow(20, n);
double top = A * (B + C);
double answer = 1 - top / bottom;

In both attempts you just got your brackets in the wrong spot.
Try this:
double answer =
1 - Math.Pow(f, n) * (s * l / f + Math.Pow((20 / f), w)) / Math.Pow(20, n);

Try to use the formula below instead :
double answer = (1 - Math.pow((Math.pow(f,n)*[s*l/f+20/f})),w)/Math.pow(20,f)

Related

Lottery winning chance exercise

So I have a problem that I'm stuck on it since 3 days ago.
You want to participate at the lottery 6/49 with only one winning variant(simple) and you want to know what odds of winning you have:
-at category I (6 numbers)
-at category II (5 numbers)
-at category III (4 numbers)
Write a console app which gets from input the number of total balls, the number of extracted balls, and the category, then print the odds of winning with a precision of 10 decimals if you play with one simple variant.
Inputs:
40
5
II
Result I must print:
0.0002659542
static void Main(string[] args)
{
int numberOfBalls = Convert.ToInt32(Console.ReadLine());
int balls = Convert.ToInt32(Console.ReadLine());
string line = Console.ReadLine();
int theCategory = FindCategory(line);
double theResult = CalculateChance(numberOfBalls, balls, theCategory);
Console.WriteLine(theResult);
}
static int FindCategory (string input)
{
int category = 0;
switch (input)
{
case "I":
category = 1;
break;
case "II":
category = 2;
break;
case "III":
category = 3;
break;
default:
Console.WriteLine("Wrong category.");
break;
}
return category;
}
static int CalculateFactorial(int x)
{
int factorial = 1;
for (int i = 1; i <= x; i++)
factorial *= i;
return factorial;
}
static int CalculateCombinations(int x, int y)
{
int combinations = CalculateFactorial(x) / (CalculateFactorial(y) * CalculateFactorial(x - y));
return combinations;
}
static double CalculateChance(int a, int b, int c)
{
double result = c / CalculateCombinations(a, b);
return result;
}
Now my problems: I'm pretty sure I have to use Combinations. For using combinations I need to use Factorials. But on the combinations formula I'm working with pretty big factorials so my numbers get truncated. And my second problem is that I don't really understand what I have to do with those categories, and I'm pretty sure I'm doing wrong on that method also. I'm new to programming so please bare with me. And I can use for this problem just basic stuff, like conditions, methods, primitives, arrays.
Let's start from combinatorics; first, come to terms:
a - all possible numbers (40 in your test case)
t - all taken numbers (5 in your test case)
c - category (2) in your test case
So we have
t - c + 1 for numbers which win and c - 1 for numbers which lose. Let's count combinations:
All combinations: take t from a possible ones:
A = a! / t! / (a - t)!
Winning numbers' combinations: take t - c + 1 winning number from t possible ones:
W = t! / (t - c + 1)! / (t - t + c - 1) = t! / (t - c + 1)! / (c - 1)!
Lost numbers' combinations: take c - 1 losing numbers from a - t possible ones:
L = (a - t)! / (c - 1)! / (a - t - c + 1)!
All combinations with category c, i.e. with exactly t - c + 1 winning and c - 1 losing numbers:
C = L * W
Probability:
P = C / A = L * W / A =
t! * t! (a - t)! * (a - t)! / (t - c + 1)! / (c - 1)! / (c - 1)! / (a - t- c + 1)! / a!
Ugh! Not let's implement some code for it:
Code:
// double : note, that int is too small for 40! and the like values
private static double Factorial(int value) {
double result = 1.0;
for (int i = 2; i <= value; ++i)
result *= i;
return result;
}
private static double Chances(int a, int t, int c) =>
Factorial(a - t) * Factorial(t) * Factorial(a - t) * Factorial(t) /
Factorial(t - c + 1) /
Factorial(c - 1) /
Factorial(c - 1) /
Factorial(a - t - c + 1) /
Factorial(a);
Test:
Console.Write(Chances(40, 5, 2));
Outcome:
0.00026595421332263435
Edit:
in terms of Combinations, if C(x, y) which means "take y items from x" we
have
A = C(a, t); W = C(t, t - c + 1); L = C(a - t, c - 1)
and
P = W * L / A = C(t, t - c + 1) * C(a - t, c - 1) / C(a, t)
Code for Combinations is quite easy; the only trick is that we return double:
// Let'g get rid of noisy "Compute": what else can we do but compute?
// Just "Combinations" without pesky prefix.
static double Combinations(int x, int y) =>
Factorial(x) / Factorial(y) / Factorial(x - y);
private static double Chances(int a, int t, int c) =>
Combinations(t, t - c + 1) *
Combinations(a - t, c - 1) /
Combinations(a, t);
You can fiddle the solution

C# trigonometric functions / math functions

I'm writing a class which should calculate angles (in degrees), after long trying I don't get it to work.
When r = 45 & h = 0 sum should be around 77,14°
but it returns NaN - Why? I know it must be something with the Math.Atan-Method and a not valid value.
My code:
private int r = 0, h = 0;
public Schutzwinkelberechnung(int r, int h)
{
this.r = r;
this.h = h;
}
public double getSchutzwinkel()
{
double sum = 0;
sum = 180 / Math.PI * Math.Atan((Math.Sqrt(2 * h * r - (h * h)) - r * Math.Sin(Math.Asin((Math.Sqrt(2 * h * r)) / (2 * r)))) / (h - r + r * (Math.Cos(Math.Asin(Math.Sqrt(2 * h * r) / (2 * r))))));
return sum;
}
Does someone see my mistake? I got the formula from an excel sheet.
EDIT: Okay, my problem was that I had a parsing error while creating the object or getting the user input, apparently solved it by accident. Ofc I have to add a simple exception, as Nick Dechiara said. Thank you very much for the fast reply, I appreciate it.
EDIT2: The exception in my excel sheet is:
if(h < 2) {h = 2}
so that's explaining everything and I wasn't paying attention at all. Thanks again for all answers.
int r = 45, h = 2;
sum = 77.14°
A good approach to debugging these kinds of issues is to break the equation into smaller pieces, so it is easier to debug.
double r = 45;
double h = 0;
double sqrt2hr = Math.Sqrt(2 * h * r);
double asinsqrt2hr = Math.Asin((sqrt2hr) / (2 * r));
double a = (Math.Sqrt(2 * h * r - (h * h)) - r * Math.Sin(asinsqrt2hr));
double b = (h - r + r * (Math.Cos(asinsqrt2hr)));
double sum = 180 / Math.PI * Math.Atan(a / b);
Now if we put a breakpoint at sum and let the code run, we see that both a and b are equal to zero. This gives us a / b = 0 / 0 = NaN in the final line.
Now we can ask, why is this happening? Well in the case of b you have h - r + r which is 0 - 45 + 45, evaluates to 0, so b becomes 0. You probably have an error in your math there.
In the case of a, we have 2 * h * r - h * h, which also evaluates to 0.
You probably either A) have an error in your equation, or B) need to include a special case for when h = 0, as that is breaking your math here.
Definitely break up the expression something like
var a = Asin(Sqrt(2 * h * r) / (2 * r));
var b = Sqrt(2 * h * r - h * h) - r * Sin(a);
var c = h - r + r * Cos(a);
var sum = 180 / PI * Atan(b / c);
and you will find b=0 and c=0. You might consider changing the last expression into
var sum = 180 / PI * Atan2(b , c);
which will return a value when b=0 and c=0.
PS. Also, use using static System.Math; in the beginning of the code to shorten such math expressions.

How should i search through a string for a sequence of characters such as "x*y"?

I am trying to make a determinat calculator using mathematical Cramer's theorem, as you can see I translated the theorem into code convertedString = Convert.ToString (x * y1 * 1 + x1 * y2 * 1 + x2 * x * y - (1 * y1 * x2 + 1 * y2 * y + 1 * y * x1));All good until I am at the point where I need to compute 2 unknown numbers, I don't know how to "tell" in code to the computer that x + x = 2x or 3y-y = 2y, so I tought that if I convert the Crammer's equation into a string I can find all the matches like x + x or y + 2y or y * y and begin from that a solution that can solve my initial problem, like if I find an x * x pattern I will tell the pc through an if statement or something that the pattern x * x is x^2.
So that being said, I want to find out the number of specific sequences like X * y or y + x that are present in a string, I did try some foreach loops and for loops but I can't get it to work and I don't know how should I approach the problem next, plase help.
Here is my code:
using System;
using InputMath;
namespace MathWizard
{
class Determinants
{
//Determinant of a first point and a second graphical point on the xoy axis.
public static void BasicDeterminant()
{
float x;
float y;
float x1 = Input.x1;
float y1 = Input.y1;
float x2 = Input.x2;
float y2 = Input.y2;
float result;
string convertedString;
string pointsValue;
string[] point;
Console.WriteLine("Please introduce the 2 graphical points ( A and B) \n in the order x1 y1 x2 y2, separated by a space ");
pointsValue = Console.ReadLine();
point = pointsValue.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
x1 = Convert.ToInt32(point[0]);
y1 = Convert.ToInt32(point[1]);
x2 = Convert.ToInt32(point[2]);
y2 = Convert.ToInt32(point[3]);
//The Cramer's Rule for solving a 2 points determinant ( P1(x1,y1) and P2(x2,y2)
convertedString = Convert.ToString (x * y1 * 1 + x1 * y2 * 1 + x2 * x * y - (1 * y1 * x2 + 1 * y2 * y + 1 * y * x1));
}
}
}
You could also use the following regex which will find x*y with case insensitivity for each operator:
string pattern = /(x(\*|\+|\-|\/|\^)y)/gi;
then you could do some string.Contains(pattern); to check. Let me know if this helps.
Edit: Updated Pattern
Updated the pattern so that it will also allow variables such as y9 or X10. Any single character (x or y) followed by any amount of numbers.
string pattern =/(x\d*(\*|\+|\-|\/|\^)y\d*)/gi; // could match X1*y9
This doesn't account for whitespaces so you could use some .replace() to get rid of whitespace or use .split(/\s/) and get a string array without whitespace before using this pattern.
bool found = false;
int xyCount = 0;
if(convertedString.Contains("X*Y")){
found = true;
xyCount++;
//makes a substring without the first case of the "X*Y"
string s = convertedString.SubString(convertedString.IndexOf("X*Y"))
if(s.Contains("X*Y")){
xyCount++;
}
Its probably not the best way to do it, but you can probably make a better method doing something like this

Exponential Moving Average with different kernels

I am trying to replicate some formulas but am having trouble translating the math to code.
Here is the simple Exponential Moving Average
In c#:
out[1] = values[1];
for (i in 2:N(X)) {
tmp = (times[i] - times[i-1]) / tau;
w = exp(-tmp);
w2 = (1 - w) / tmp;
out[i] = out[i-1] * w + values[i] * (1 - w2) + values[i-1] * (w2 - w);
}
In Python:
mu = numpy.exp ((ts[1] - ts[0]) / self.tau)
nu = 1.0 - mu
return numpy.array ([
mu * el + nu * arr[0] for el, arr in zip (last, arrays)
])
I want to be able to specify different kernels and am not sure how to go about it as described here:
This is all done so I can eventually recreate this moving differential given here:
Thanks for any help given
One possible approach here is to have a method that returns the kernel.
From what I am able to see, inputs to this method would be kerneltype, i, and otherInputs.
A simple approach would be:
for(int i = 1; i < values.length(); i++)
{
tmp = (times[i] - times[i-1]) / tau;
//w = exp(-tmp);
//w2 = (1 - w) / tmp;
List<Object> kernelInputsInital = new List<Object>();
kernelInputsInitial.Add(tmp); //takes in the first argument
kernelInputsInitial.Add(true); //expected to calculate the first
w = GetKernel(KernelType.Exponential, i, kernelInputsInitial);
List<Object> kernelInputsSecondTerm = new List<Object>();
kernelInputsSecondTerm.Add(w); //takes in the first argument
kernelInputsSecondTerm.Add(false); //expected to calculate the first
w2 = GetKernel(KernelType.Exponential, i, kernelInputsInitial);
out[i] = out[i-1] * w + values[i] * (1 - w2) + values[i-1] * (w2 - w);
....
}
This is of course terribly, terribly rough, and a lot of improvement can be made, but it is intended to merely get the point across.
I would use an interface to represent a kernel, and have classes derived per kernel. In my experience, that produces sufficiently readable and maintainable code, but there's always room for improvement.

.NET math calculation performances

I asked a question about having the Excel's BetaInv function ported to .NET: BetaInv function in SQL Server
now I managed to write that function in pure dependency less C# code and I do get the same results than in MS Excel up to 6 or 7 digits after comma, results are fine for us, the problem is that such code is embedded in a SQL CLR Function and gets called thousands of time from a stored procedure and makes the execution of the whole procedure about 50% slower, from 30 seconds up to a minute if I use that function or not.
here some code of it, I am not asking a deep analysis but is there anybody who sees any major performance issue in the way I am doing this calculations? like for example usage of other data types instead of doubles or whatsoever... ?
private static double betacf(double a, double b, double x)
{
int m, m2;
double aa, c, d, del, h, qab, qam, qap;
qab = a + b;
qap = a + 1.0;
qam = a - 1.0;
c = 1.0; // First step of Lentz’s method.
d = 1.0 - qab * x / qap;
if (System.Math.Abs(d) < FPMIN)
{
d = FPMIN;
}
d = 1.0 / d;
h = d;
for (m = 1; m <= MAXIT; ++m)
{
m2 = 2 * m;
aa = m * (b - m) * x / ((qam + m2) * (a + m2));
d = 1.0 + aa * d; //One step (the even one) of the recurrence.
if (System.Math.Abs(d) < FPMIN)
{
d = FPMIN;
}
c = 1.0 + aa / c;
if (System.Math.Abs(c) < FPMIN)
{
c = FPMIN;
}
d = 1.0 / d;
h *= d * c;
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2));
d = 1.0 + aa * d; // Next step of the recurrence (the odd one).
if (System.Math.Abs(d) < FPMIN)
{
d = FPMIN;
}
c = 1.0 + aa / c;
if (System.Math.Abs(c) < FPMIN)
{
c = FPMIN;
}
d = 1.0 / d;
del = d * c;
h *= del;
if (System.Math.Abs(del - 1.0) < EPS)
{
// Are we done?
break;
}
}
if (m > MAXIT)
{
return 0;
}
else
{
return h;
}
}
private static double gammln(double xx)
{
double x, y, tmp, ser;
double[] cof = new double[] { 76.180091729471457, -86.505320329416776, 24.014098240830911, -1.231739572450155, 0.001208650973866179, -0.000005395239384953 };
y = xx;
x = xx;
tmp = x + 5.5;
tmp -= (x + 0.5) * System.Math.Log(tmp);
ser = 1.0000000001900149;
for (int j = 0; j <= 5; ++j)
{
y += 1;
ser += cof[j] / y;
}
return -tmp + System.Math.Log(2.5066282746310007 * ser / x);
}
The only thing that stands out for me, and is usually a performance hit, is memory allocation. I don't know how often gammln is called but you might want to move the double[] cof = new double[] {} to a static one time only allocation.
double is usually the best type. Especially since the functions in Math take doubles. Unfortunately I see no obvious improvements to make on your code.
It might be possible to use look up tables to get a better first estimate on which you iterate, but since I don't know the Math behind what you're doing I don't know if that's possible in this specific case.
Obviously larger epsilons will improve performance. So choose it as large as possible while fulfilling your accuracy demands.
If the function gets called repeatedly with the same parameters you might be able to cache results.
One thing that looks odd is the way you force small values for c, d,... to FPMIN. My instinct is that this might lead to suboptimal step sizes.
All I've got is unrolling the j loop in gammln, but it'll make at most a tiny difference.
A more radical thought would be to rewrite in pure T-SQL, since it has everything you use: + - * / abs log are all available.

Categories

Resources