entering a string to be used as a formula , in c# - c#

I've found the shunting yard algorithm, but it feels like case is a little bit different.
What if the formula your entering has variables that you want to use in another formula
you enter
cout<<"enter string"<<endl;
cin>>f;
and you enter f as
3 * (X*X) + 2*X + 7
and you use that string and parse it to find the root, for example.

While it is hard to understand what you are looking for, it hints at the ability to evaluate strings as formulas. If your looking for an Eval like solution, take a look at nCalc. Stealing from their webpage:
Expression e = new Expression("2 + 3 * 5");
Debug.Assert(17 == e.Evaluate());
It also allows you to use parameters, like
e.Parameters["X"] = 10;
and then use X as part of your string to evaluate.
It let's you convert a string representing a formula into it's final value. If you are not asking about interpreting strings at formulas then I am at a loss for what you are asking. I recommend revising your question to better articulate the inputs and outputs of your proposed functionality.

One solution that comes to my mind is, may be you can create a valid C# code from that string at runtime and make it compile, and make it execute. For example your code cam become in memory like
using namespace FormulaCalculator
{
public class Calculator
{
public static object Calculate()
{
return 3 * (X*X) + 2*X + 7 ; //where X is replaced value at runtime.
}
}
}
Compile this with CodeDome in in-memory assembly and run. Here an example Example
object resultOfFormula = FormulaCalculator.Calculator.Calculate()

Related

Refer to a specific index of an array depending on user input

Trying to make a program where it takes in an equation from user and outputs the answer. Having to develop all code for it to work, and wondering how I could refer to either array index value either side of a specific index?
Example:
User input: X = 5 + 5 * 6
Wanting to be able to locate the ***** and retrieve the value of the 5 & 6 either side of it. Tried multiple things and tried searching here too, cannot find a answer.
Thankyou in advance to anyone who takes the time to help!
One way to do it is to use regular expressions. I would remove all whitespaces first to make it easier. For example:
string input = "X = 5 + 5 * 6";
Regex r = new Regex(#"(\d+)\*(\d+)");
Match m = r.Match(input.Replace(" ", ""));
var a = m.Groups[1].Value; // a = 5
var b = m.Groups[2].Value; // b = 6
Explanation of this regex can be found here: https://regex101.com/r/k7rthI/1
You would have to improve the regex to handle decimals and many other cases when the equation gets more complex. It is a long dark rabbit hole to go down if you get more complex than what you have. So you might be better off finding a math library you can use. No reason to reinvent the wheel.

MathDotNet: Sampling from distributions without casting

How does one sample from a distribution in MathDotNet without having to cast to the specific distribution?
I have a distribution d which could be any random variable, being passed around as an IDistribution. Now, I wish to sample from it. I want to do this with having to do as few casts as possible on the actual distribution itself (I don't want a giant case statement with a ton of casts to really specific distribution types like Bernoulli, Normal, etc.
I have tried the following code, for an IDistribution d who is of type Bernoulli, with a mean of around 0.99:
Console.WriteLine("Mean is " + ((Bernoulli)d).Mean);
Console.WriteLine("Casted sample is " + ((Bernoulli)d).Sample());
Console.WriteLine("Sample is " + d.RandomSource.NextDouble());
The first print statement prints 0.99, as expected.
The second print statement tends to return 1, as expected, since 99% of the time it should return 1.
The third print statement seems to be giving me what looks like a uniform random variable between 0 or 1 (NB: It might not be uniform, that's just with a quick eyeball test on print statements, but it's definitely NOT Bernoulli with mean 0.99).
How can I sample generally from the appropriate distribution?
This is what I am currently doing. I would like to avoid the if statement, but for now, this works. If someone has a better answer, it would be preferable:
if (distribution is IContinuousDistribution){
value = (double)((IContinuousDistribution)distribution).Sample();
}else{
value = (double)((IDiscreteDistribution)distribution).Sample();
}

.NET query getting inappropriate answer

I was at career fair and I was asked a question "what does this query do and in which language it is".
I told that it is in .NET LINQ, but was unable to predict what it does.
Can any one help me
I wrote in .NET and tried .
var youShould = from c
in "3%.$#9/52#2%35-%#4/#./3,!#+%23 !2#526%N#/-"
select (char)(c ^ 3 << 5);
Label1.Text = youShould.ToString();
And got this output :
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Char,System.Char]
First of all, don't feel bad that you didn't get the answer. I know exactly what's going on here and I'd have probably just laughed and walked away if someone asked me what this did.
There's a number of things going on here, but start with the output:
var youShould = from c in "3%.$#9/52#2%35-%#4/#./3,!#+%23 !2#526%N#/-"
select (char)(c ^ 3 << 5);
Label1.Text = youShould.ToString();
>>> System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Char,System.Char]
When you run a LINQ query, or use any of the equivalent methods like Select() that return sets, what you get back is a special, internal type of object called an "iterator", specifically, an object that implements the IEnumerable interface. .NET uses these objects all over the place; for example, the foreach loop's purpose is to iterate over iterators.
One of the most important things to know about these kind of objects is that just creating one doesn't actually "do" anything. The iterator doesn't actually contain a set of things; rather, it contains the instructions needed to produce a set of things. If you try to do something like, e.g. ToString on it, the result you get won't be very useful.
However, it does tell us one thing: it tells us that this particular iterator takes a source list of type char and returns a new set, also of type char. (I know that because I know that's what the two generic parameters of a "select iterator" do.) To get the actual results out of this iterator you just need to loop over it somehow, e.g.:
foreach (var c in youShould)
{
myLabel.Text += c;
}
or, slightly easier,
myLabel.Text = new string(youShould.ToArray());
To actually figure out what it does, you have to also recognize the second fact: LINQ treats a string as a "set of characters". It is going to process each character in that string, one at a time, and perform the bit-wise operations on the value.
The long-form equivalent of that query is something like this:
var input= "3%.$#9/52#2%35-%#4/#./3,!#+%23 !2#526%N#/-";
var output = string.Empty;
foreach (var c in input)
{
var i = (int)c;
var i2 = i ^ (3 << 5);
var c2= (char)i2;
output += c2;
}
If you did the math by hand you'd get the correct output message. To save you the brain-numbing exercise, I'll just tell you: it toggles bits 5 and 6 of the ASCII value, changing each character to one further up the ASCII table. The resulting string is:
SEND YOUR RESUME TO [an email address]
Demostrative .NET Fiddle: https://dotnetfiddle.net/x7UvYA
For each character in the string, project the character by xor-ing it with (3 left shifted by 5), then cast the numeric value back to a char.
You could generate your own code strings by running the query again over an uncoded string, because if you XOR a number twice by the same value, you'll be left with the same number you started with. (e.g. x ^ y ^ y = x)
I'll leave it as an exercise to the reader to figure out what the following is:
4()3#)3#!#$5-"#4%34
I suppose it tests:
Linq to objects
Understanding of IEnumerable<T> interface and how it relates to strings
Casting
Bitwise operations
Bitwise operator precedence
Personally, I think this is a useless test that doesn't really reflect real world problems.

Remove Trailing Zeros from a Double Value

I have encountered a problem in a solution that I am trying to achieve, namely I need to be able to remove trailing zeros from a double value using C#.
For instance, if I were creating two objects that represent a formula, it would be appropriate to say that the two formulas (2.0 + 7) and (2.000 + 7) are equivalent. That is, (2.0 + 7) == (2.00000 + 7). However, I'm not sure the best way to approach this is. I'm thinking regular expressions, but I'm not certain that I can get the outcome I am looking for.
It seems that there would be an issue with resolution in this case. As an example, the two formulas 2.0 + 7 and 2.000000001 + 7 aren't the same, but they are extremely close. So my question is, could a regular expression account for this? Likewise, would a regular expression be the best approach?
With more elaboration, the following should be legal.
Assert.IsTrue(new Formula("2.0 + x7").Equals(new Formula("2.000 + x7")))
Within the Formula class there is a field that stores reference to a List of strings. This list must contain the same value in order for the overridden "Equals" method to return true.
You don't need RegExp, just use Math.Round(Double, Int32).
Try this :
double num = 587.21500;
var res = Double.Parse(num.ToString("G29"));
double variable = 56.123456;
string twoplaces = String.Format("{0:0.##}", variable);
?

solving a math expression

I want to evaluate a math expression which the user enters in a textbox. I have done this so far
string equation, finalString;
equation = textBox1.Text;
StringBuilder stringEvaluate = new StringBuilder(equation);
stringEvaluate.Replace("sin", "math.sin");
stringEvaluate.Replace("cos", "math.cos");
stringEvaluate.Replace("tan", "math.tan");
stringEvaluate.Replace("log", "math.log10");
stringEvaluate.Replace("e^", "math.exp");
finalString = stringEvaluate.ToString();
StringBuilder replaceI = new StringBuilder(finalString);
replaceI.Replace("x", "i");
double a;
for (int i = 0; i<5 ; i++)
{
a = double.Parse(finalStringI);
if(a<0)
break;
}
when I run this program it gives an error "Input string was not in a correct format." and highlights a=double.Parse(finalStringI);
I used a pre defined expression a=i*math.log10(i)-1.2 and it works, but when I enter the same thing in the textbox it doesn't.
I did some search and it came up with something to do with compiling the code at runtime.
any ideas how to do this?
i'm an absolute beginner.
thanks :)
The issue is within your stringEvaluate StringBuilder. When you're replacing "sin" with "math.sin", the content within stringEvaluate is still a string. You've got the right idea, but the error you're getting is because of that fact.
Math.sin is a method inside the Math class, thus it cannot be operated on as you are in your a = double.Parse(finalStringI); call.
It would be a pretty big undertaking to accomplish your goal, but I would go about it this way:
Create a class (perhaps call it Expression).
Members of the Expression class could include Lists of operators and operands, and perhaps a double called solution.
Pass this class the string at instantiation, and tear it apart using the StringBuilder class. For example, if you encounter a "sin", add Math.sin to the operator collection (of which I'd use type object).
Each operator and operand within said string should be placed within the two collections.
Create a method that evaluates the elements within the operator and operand collection accordingly. This could get sticky for complex calculations with more than 2 operators, as you would have to implement a PEMDAS-esque algorithm to re-order the collections to obey the order of operations (and thus achieve correct solutions).
Hope this helps :)
The .Parse methods (Int.Parse, double.Parse, etc) will only take a string such as "25" or "3.141" and convert it to the matching value type (int 25, or double 3.141). They will not evaluate math expressions!
You'll pretty much have to write your own text-parser and parse-tree evaluator, or explore run-time code-generation, or MSIL code-emission.
Neither topic can really be covered in the Q&A format of StackOverflow answers.
Take a look at this blog post:
http://www.c-sharpcorner.com/UploadFile/mgold/CodeDomCalculator08082005003253AM/CodeDomCalculator.aspx
It sounds like it does pretty much what you're trying to do. Evaluating math expressions is not as simple as just parsing a double (which is really only going to work for strings like "1.234", not "1 + 2.34"), but apparently it is possible.
You can use the eval function that the framework includes for JScript.NET code.
More details: http://odetocode.com/code/80.aspx
Or, if you're not scared to use classes marked "deprecated", it's really easy:
static string EvalExpression(string s)
{
return Microsoft.JScript.Eval.JScriptEvaluate(s, null, Microsoft.JScript.Vsa.VsaEngine.CreateEngine()).ToString();
}
For example, input "Math.cos(Math.PI / 3)" and the result is "0.5" (which is the correct cosine of 60 degrees)

Categories