I'm working with ILNumerics and I created a console app with .NET 6.0 like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ILNumerics;
using ILNumerics.Toolboxes;
namespace ConsoleApp1
{
internal class ppbkc
{
static void Main(string[] args)
{
RetArray<double> maxPos_fun(InArray<double> x)
{
using (Scope.Enter(x))
{
double out_ = (double)((double)(ILMath.log((double)mu) -ILMath.log((double)x))/(mu - x));
return out_;
}
}
RetArray<double> beta3_func(InArray<double> x)
{
using (Scope.Enter(x))
{
double out_ = Math.Pow((double)(maxPos_fun(x) - 1 / mu), 2);
return out_;
}
}
List<double> beta = new List<double>();
InArray<double> bounds = new double[] { 0, 1000 };
InArray<double> start = new double[] { 1 };
beta.Add((double)Optimization.fmin(beta3_func, start,
lowerBound: bounds[0], upperBound: bounds[1]));
}
}
}
Also muis Fixed variable.
I got this exception:
System.ArgumentOutOfRangeException: 'Specified argument was out of the range of valid values. (Parameter 'ILNumerics.fmin: The function produced undefined result at: [1,1]
-0.127557')'
And it is about this line:
beta.Add((double)Optimization.fmin(beta3_func, start,
lowerBound: bounds[0], upperBound: bounds[1]));
enter image description here
What does this mean and how can I solve it?
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Hi fellow programmers,
I am creating a calculator in C#
and I have a string variable math which contains 100 * 5 - 2
How can I display its output which is 498 in my console?
My code is this:
String math = "100 * 5 - 2";
Console.WriteLine(math);
Console.ReadLine(); // For Pause
So basically, what my code will give me is the string itself which 100 * 5 - 2
but I want it to give me 498 as a result.
Idea about this is pretty much appreciated.
Thanks
Regular Expression evaluation can be done using DataTable.Compute method (from MSDN) :
Computes the given expression on the current rows that pass the filter
criteria.
Try this:
using System.Data;//import this namespace
string math = "100 * 5 - 2";
string value = new DataTable().Compute(math, null).ToString();
Simply try this
String math = (100 * 5 - 2).ToString();
I don't know, Why you want more complex? It's very easy ..
And if you want surely that,You can do that by using EvaluateExpression
public int EvaluateExpression(string math )
{
return Convert.ToInt32(math);
}
........................
String math = "100 * 5 - 2";
int result = EvaluateExpression(math );
Console.WriteLine(result );
See this discussions
Evaluating string "3*(4+2)" yield int 18
Update:
If those values came from input textbox, then write this way
String math = txtCalculator.Text.Trim();
int result = EvaluateExpression(math );
Console.WriteLine(result );
And also you can find out some pretty answer from this discussion
Is it possible to compile and execute new code at runtime in .NET?
Update 2:
Finally I have tried this sample for you :
My full code for class library
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.XPath;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
String math = "100 * 5 - 2";
Console.WriteLine(Evaluate(math));
}
public static double Evaluate(string expression)
{
var xsltExpression =
string.Format("number({0})",
new Regex(#"([\+\-\*])").Replace(expression, " ${1} ")
.Replace("/", " div ")
.Replace("%", " mod "));
// ReSharper disable PossibleNullReferenceException
return (double)new XPathDocument
(new StringReader("<r/>"))
.CreateNavigator()
.Evaluate(xsltExpression);
// ReSharper restore PossibleNullReferenceException
}
}
You can compile code from string at runtime and execute it:
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace DynamicCalcTest
{
class Program
{
static void Main(string[] args)
{
var result = new DynamicCalculator<double>("2 + 2 * 2").Execute();
}
}
public class DynamicCalculator<T>
{
private MethodInfo _Method = null;
public DynamicCalculator(string code)
{
_Method = GetMethodInfo(code);
}
public T Execute()
{
return (T)_Method.Invoke(null, null);
}
private MethodInfo GetMethodInfo(string code)
{
var tpl = #"
public static class Calculator
{{
public static double Calc()
{{
return {0};
}}
}}";
var finalCode = string.Format(tpl, code);
var parameters = new CompilerParameters();
parameters.ReferencedAssemblies.Add("mscorlib.dll");
parameters.GenerateInMemory = true;
parameters.CompilerOptions = "/platform:anycpu";
var options = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } };
var c = new CSharpCodeProvider(options);
var results = c.CompileAssemblyFromSource(parameters, finalCode);
var type = results.CompiledAssembly.GetExportedTypes()[0];
var mi = type.GetMethod("Calc");
return mi;
}
}
}
i would like to access to the coordinate information in a LinePlot, i wanto to use the Property LinePlot.Positions as show in the following code:
using System;
using System.Collections.Generic;
using System.Text;
using ILNumerics.Data;
using ILNumerics.Drawing.Plotting;
using ILNumerics.Drawing;
using ILNumerics;
using static ILNumerics.ILMath;
using System.Linq;
namespace TestConsoleUI2
{
class Program
{
static void Main(string[] args)
{
Array<double> xx = linspace(10, 15, 5);
Array<double> yy = linspace(8, 90, 5);
LinePlot myLinePlot = new LinePlot(xx, yy);
RetArray<float> p = myLinePlot.Positions;
}
}
}
Nevertheless i got an System.NullReferenceException i have debugged and the data exists at that moment,
can anyone help me?
Regards
After try and error i found the solution that is working for me.
using System;
using System.Collections.Generic;
using System.Text;
using ILNumerics.Data;
using ILNumerics.Drawing.Plotting;
using ILNumerics.Drawing;
using ILNumerics;
using static ILNumerics.ILMath;
using System.Linq;
namespace TestConsoleUI2
{
class Program
{
static void Main(string[] args)
{
Array<double> xx = linspace(10, 15, 5);
Array<double> yy = linspace(8, 90, 5);
LinePlot myLinePlot = new LinePlot(xx, yy);
PositionsBuffer p = myLinePlot.Line.Positions;
}
}
}
I have this number in C#
Double a = 1.2345678
What I would like is for it to look like this after it's made into a string:
1.23456
First, convert it to string.
for example the string is defined as S.
then apply this method:
S.Remove(S.Length -2);
You can acheive that in many ways:
Code:
using System;
using System.Linq;
using System.Text;
namespace RemovingLastTwoNumber
{
class Program
{
static void Main(string[] args)
{
// Method 1.
double number = 1.2345678;
string numberInStringFormat = number.ToString();
string TargetNumber = numberInStringFormat.Substring(0, numberInStringFormat.Length - 2);
Console.WriteLine(number);
Console.WriteLine(TargetNumber);
// Method 2.
string _TargetNumber = Math.Round(number, 5).ToString();
Console.WriteLine(_TargetNumber);
// Method 3.
var characters = number.ToString().ToArray();
var __Characters = characters.Take(7);
StringBuilder __targetNumber = new StringBuilder();
foreach (var character in __Characters)
{
__targetNumber.Append(character);
}
Console.WriteLine(__targetNumber);
}
}
}
I need help linking or mapping a combo box to a parallel array in C#. I have a class project where I need to create a payroll system that displays the Net Pay after taxes.
I want to link parallel arrays that have all the employee information needed for payroll to the option selected in the combo box. I feel like I almost have it, but I don't know how to link the option selected from the combo box and the parallel arrays I have set up.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ZNSPayrollSystem
{
public partial class ZNSPayrollSystem : Form
{
public ZNSPayrollSystem()
{
InitializeComponent();
string[] arr = { "001 Peters", "002 Barnes", "003 Harris" };
cboEmp.DataSource = arr.ToArray();
}
private void btnCalc_Click(object sender, EventArgs e)
{
//parallel arrays
int[] empID = { 001, 002, 003 };
string[] empName = { "James Peters", "Sarah Barnes", "Candice Harris" };
double[] hrsWorked = { 40, 40, 40 };
double[] empWage = { 55.50, 65.50, 75.70 };
//declarations
double dblTaxRate = 8.2 / 100;
double dblNetPay;
double dblGrossPay;
double dblTaxWithheld;
dblGrossPay = hrsWorked[] * empWage[];
dblTaxWithheld = dblGrossPay * dblTaxRate;
dblNetPay = dblGrossPay - dblTaxWithheld;
txtGross.Text = dblGrossPay.ToString();
txtTax.Text = dblTaxWithheld.ToString();
txtNetPay.Text = dblNetPay.ToString();
}
}
}
Use the SelectedIndex property of the Combobox:
int i = cboEmp.SelectedIndex;
if (i != -1)
{
dblGrossPay = hrsWorked[i] * empWage[i];
}
i == -1 means nothing is selected. You may want to handle this separately to avoid getting any exceptions.
Hello I would like to convert this vba method into C#. I am trying to get the IDs of a selection and print them out. In particular I am having trouble converting the GetIDs() method(a built in method within visio vba) into C#.
Public Sub getCapabilityRectIDs()
Dim vsoSelection1 As Visio.Selection
Dim selectionIDs() As Long
Set vsoSelection1 = Application.ActiveWindow.Page.CreateSelection(visSelTypeByLayer, visSelModeSkipSuper, "Capability")
Application.ActiveWindow.Selection = vsoSelection1
Call vsoSelection1.GetIDs(selectionIDs)
For i = 0 To UBound(selectionIDs)
Debug.Print selectionIDs(i)
Next i
End Sub
This is what I have so far in C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Visio = Microsoft.Office.Interop.Visio;
class Program
{
static void Main(string[] args)
{
//create the object that will do the drawing
VisioDrawer Drawer = new VisioDrawer();
Drawer.selectShpLayer("Capability");
}
}
class VisioDrawer
{
public Visio.Application VisApp;
public static Visio.Page acPage;
public Visio.Selection LayerSelection;
public VisioDrawer()
{
//create the application
VisApp = new Visio.Application();
VisApp.Documents.Open(#"............. - abc.vsdm");
ActiveDoc = VisApp.ActiveDocument;
acPage = VisApp.ActivePage;
}
public void selectShpLayer (string layerName){
Int i = 0;
long[] lngRowIDs;
//this selects the shapes of the selected layer
LayerSelection = acPage.CreateSelection(Microsoft.Office.Interop.Visio.VisSelectionTypes.visSelTypeByLayer, Microsoft.Office.Interop.Visio.VisSelectMode.visSelModeOnlySuper,layerName);
LayerSelection.GetIDs(lngRowIDs);
for (i = 0; i < lngRowIDs.Length; i++)
{
Debug.Write(lngRowIDs[i]);
}
}
}
Thanks in advance!
I created a visio doc and drew 3 simple shapes. I then created a layer called "cool" and added those 3 shapes to it.
I don't understand enough about the shape selection, you had visSelModeOnlySuper which may work for you, but did not work for the case I created. The default is visSelModeSkipSuper (which worked for me)
Here's the API page that describes how to use the createSelection:
https://msdn.microsoft.com/en-us/library/office/ff765565.aspx
Here is my sample code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Visio = Microsoft.Office.Interop.Visio;
class Program
{
static void Main(string[] args)
{
//create the object that will do the drawing
VisioDrawer Drawer = new VisioDrawer();
Drawer.selectShpLayer("cool");
}
}
class VisioDrawer
{
public Visio.Application VisApp;
public static Visio.Page acPage;
public Visio.Selection LayerSelection;
public VisioDrawer()
{
//create the application
VisApp = new Visio.Application();
VisApp.Documents.Open(#"c:\temp\trial.vsdm");
acPage = VisApp.ActivePage;
}
public void selectShpLayer(string layerName)
{
int i = 0;
int[] lngRowIDs;
Array lngRowIDArray;
//this selects the shapes of the selected layer
LayerSelection = acPage.CreateSelection(Microsoft.Office.Interop.Visio.VisSelectionTypes.visSelTypeByLayer, Microsoft.Office.Interop.Visio.VisSelectMode.visSelModeSkipSuper, layerName);
LayerSelection.GetIDs(out lngRowIDArray);
lngRowIDs = (int[])lngRowIDArray;
for (i = 0; i < lngRowIDs.Length; i++)
{
Debug.Write("Object ID: " + lngRowIDs[i].ToString() + "\n");
}
}
}
And it produces this output:
Object ID: 1
Object ID: 2
Object ID: 3
If you change the debug line to this:
Debug.Write("Object ID: " + lngRowIDs[i].ToString() + " -- " + acPage.Shapes.ItemFromID[i].Name + "\n");
The output gets even more useful:
Object ID: 1 -- ThePage
Object ID: 2 -- Circle
Object ID: 3 -- Rectangle