using System; public class MainClass { public static void Main() { Type targetType = typeof(int); object source = "42"; object result = Convert.ChangeType(source, targetType); Console.WriteLine(result); // 42 Console.WriteLine(result.GetType()); // System.Int32 } }
Month: February 2011
Hidden among the To(integral-type) methods are overloads that parse numbers in another base:
using System; public class MainClass { public static void Main() { int thirty = Convert.ToInt32("1E", 16); // parse in hexadecimal uint five = Convert.ToUInt32("101", 2); // parse in binary } }
Convert string to int
using System;
using System.Collections.Generic;
using System.Text;
class Program {
static void Main(string[] args) {
Console.WriteLine(“Enter an integer:”);
int myInt = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(“Integer less than 10? {0}”, myInt < 10);
Console.WriteLine("Integer between 0 and 5? {0}",
(0 <= myInt) && (myInt <= 5));
Console.WriteLine("Bitwise AND of Integer and 10 = {0}", myInt & 10);
}
}
[/csharp]
Class to do math on complex numbers.
/* ————————————————————————–
*
* License
*
* The contents of this file are subject to the Jabber Open Source License
* Version 1.0 (the “License”). You may not copy or use this file, in either
* source code or executable form, except in compliance with the License. You
* may obtain a copy of the License at http://www.jabber.com/license/ or at
* http://www.opensource.org/.
*
* Software distributed under the License is distributed on an “AS IS” basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Copyrights
*
* Portions created by or assigned to Cursive Systems, Inc. are
* Copyright (c) 2002 Cursive Systems, Inc. All Rights Reserved. Contact
* information for Cursive Systems, Inc. is available at http://www.cursive.net/.
*
* Portions Copyright (c) 2002 Joe Hildebrand.
*
* Acknowledgements
*
* Special thanks to the Jabber Open Source Contributors for their
* suggestions and support of Jabber.
*
* ————————————————————————–*/
namespace bedrock.util
{
using System;
///
/// the numerical methods literature. Sorry, but I've lost the citations by now.
///
public class Complex : IFormattable
{
private double m_real;
private double m_imag;
// Double.Epsilon is too small
private static double s_tolerance = 1E-15;
///
/// Both parts use double-precision.
///
/// Real part
/// Imaginary part. Multiplied by “i” and added to real.
public Complex(double real, double imag)
{
m_real = real;
m_imag = imag;
}
///
///
/// Real part
public Complex(double real) : this(real, 0.0)
{
}
///
///
/// The magnitude of the polar representation
/// The angle, in radians, of the polar representation
public static Complex Polar(double magnitude, double radianAngle)
{
return new Complex(magnitude * Math.Cos(radianAngle),
magnitude * Math.Sin(radianAngle));
}
///
///
public double Real
{
get { return m_real; }
set { m_real = value; }
}
///
///
public double Imaginary
{
get { return m_imag; }
set { m_imag = value; }
}
///
///
public Complex Conjugate()
{
return new Complex(m_real, -m_imag);
}
///
///
public double Abs()
{
return Abs(m_real, m_imag);
}
///
///
/// first number
/// second number
private static double Abs(double first, double second)
{
// avoid double math wherever possible…
//return Math.Sqrt((first * first) + (second * second));
first = Math.Abs(first);
second = Math.Abs(second);
if (first == 0d)
{
return second;
}
if (second == 0d)
{
return first;
}
if (first > second)
{
double temp = second / first;
return first * Math.Sqrt(1d + (temp * temp));
}
else
{
double temp = first / second;
return second * Math.Sqrt(1d + (temp * temp));
}
}
///
///
public double Arg()
{
return Math.Atan2(m_imag, m_real);
}
///
///
public Complex Sqrt()
{
//return Math.Sqrt(this.Abs()) *
// new Complex( Math.Cos(this.Arg()/2),
// Math.Sin(this.Arg()/2));
if ((m_real == 0d) && (m_imag == 0d))
{
return new Complex(0d, 0d);
}
else
{
double ar = Math.Abs(m_real);
double ai = Math.Abs(m_imag);
double temp;
double w;
if (ar >= ai)
{
temp = ai / ar;
w = Math.Sqrt(ar) *
Math.Sqrt(0.5d * (1d + Math.Sqrt(1d + (temp * temp))));
}
else
{
temp = ar / ai;
w = Math.Sqrt(ai) *
Math.Sqrt(0.5d * (temp + Math.Sqrt(1d + (temp * temp))));
}
if (m_real > 0d)
{
return new Complex(w, m_imag / (2d * w));
}
else
{
double r = (m_imag >= 0d) ? w : -w;
return new Complex(r, m_imag / (2d * r));
}
}
}
///
///
/// The power to raise to.
public Complex Pow(double exponent)
{
double real = exponent * Math.Log(this.Abs());
double imag = exponent * this.Arg();
double scalar = Math.Exp(real);
return new Complex(scalar * Math.Cos(imag), scalar * Math.Sin(imag));
}
///
///
/// The power to raise to.
public Complex Pow(Complex exponent)
{
double real = Math.Log(this.Abs());
double imag = this.Arg();
double r2 = (real * exponent.m_real) – (imag * exponent.m_imag);
double i2 = (real * exponent.m_imag) + (imag * exponent.m_real);
double scalar = Math.Exp(r2);
return new Complex(scalar * Math.Cos(i2), scalar * Math.Sin(i2));
}
///
///
public Complex Exp()
{
return Math.Exp(m_real) *
new Complex( Math.Cos(m_imag), Math.Sin(m_imag));
}
///
///
public Complex Inverse()
{
double scalar;
double ratio;
if (Math.Abs(m_real) >= Math.Abs(m_imag))
{
ratio = m_imag / m_real;
scalar = 1d / (m_real + m_imag * ratio);
return new Complex(scalar, -scalar * ratio);
}
else
{
ratio = m_real / m_imag;
scalar = 1d / (m_real * ratio + m_imag);
return new Complex(scalar * ratio, -scalar);
}
}
///
///
public Complex Log()
{
return new Complex(Math.Log(this.Abs()), this.Arg());
}
///
///
public Complex Sin()
{
Complex iz = this * Complex.i;
Complex izn = -iz;
return (iz.Exp() – izn.Exp()) / new Complex(0,2);
}
///
///
public Complex Cos()
{
Complex iz = this * Complex.i;
Complex izn = -iz;
return (iz.Exp() + izn.Exp()) / 2.0;
}
///
///
public Complex Tan()
{
return this.Sin() / this.Cos();
}
///
///
public Complex Sinh()
{
return (this.Exp() – (-this).Exp()) / 2d;
}
///
///
public Complex Cosh()
{
return (this.Exp() + (-this).Exp()) / 2d;
}
///
///
public Complex Tanh()
{
return this.Sinh() / this.Cosh();
}
///
///
public Complex Asin()
{
// TODO: if anyone cares about this function, some of it
// should probably be inlined and streamlined.
Complex I = i;
return -I * ((this*I) + (1 – (this * this)).Sqrt()).Log();
}
///
///
public Complex Acos()
{
// TODO: if anyone cares about this function, some of it
// should probably be inlined and streamlined.
Complex I = i;
return -I * (this + I * (1 – (this*this)).Sqrt()).Log();
}
///
///
public Complex Atan()
{
// TODO: if anyone cares about this function, some of it
// should probably be inlined and streamlined.
Complex I = i;
return -I/2 * ((I – this)/(I + this)).Log();
}
///
///
public Complex Asinh()
{
return (this + ((this*this) + 1).Sqrt()).Log();
}
///
///
public Complex Acosh()
{
return 2d * (((this+1d) / 2d).Sqrt() +
((this-1) / 2d).Sqrt()).Log();
// Gar. This one didn't work. Perhaps it isn't returning the
// “pricipal” value.
//return (this + ((this*this) – 1).Sqrt()).Log();
}
///
///
public Complex Atanh()
{
return ((1+this) / (1-this)).Log() / 2d;
}
///
///
public bool IsNaN()
{
return Double.IsNaN(m_real) || Double.IsNaN(m_imag);
}
///
///
public bool IsInfinity()
{
return Double.IsInfinity(m_real) || Double.IsInfinity(m_imag);
}
///
///
///
public override int GetHashCode()
{
return ((int)m_imag << 16) ^ (int) m_real;
}
///
///
public override string ToString()
{
return this.ToString(null, null);
}
///
///
///
///
///
public string ToString(string format, IFormatProvider sop)
{
if (this.IsNaN())
return “NaN”;
if (this.IsInfinity())
return “Infinity”;
if (m_imag == 0d)
return m_real.ToString(format, sop);
if (m_real == 0d)
return m_imag.ToString(format, sop) + “i”;
if (m_imag < 0.0)
{
return m_real.ToString(format, sop) + " - " +
(-m_imag).ToString(format, sop) + "i";
}
return m_real.ToString(format, sop) + " + " +
m_imag.ToString(format, sop) + "i";
}
///
/// Will work with other Complex numbers or doubles.
///
/// The other object to compare against. Must be double or Complex.
public override bool Equals(object other)
{
if (other is Complex)
{
Complex o = (Complex) other;
// performance optimization for “identical” numbers”
if ((o.m_real == m_real) && (o.m_imag == m_imag))
return true;
return Equals(o, s_tolerance);
}
double d = (double) other; // can fire exception
if (m_imag != 0.0)
return false;
return Math.Abs(m_real – d) < s_tolerance;
}
///
///
/// The other Complex to comapare against.
/// The tolerance to be within.
public bool Equals(Complex other, double tolerance)
{
return (this – other).Abs() < tolerance;
}
///
///
/// Complex
/// Complex
public static bool operator==(Complex first, Complex second)
{
return first.Equals(second);
}
///
///
/// Complex
/// Complex
public static bool operator!=(Complex first, Complex second)
{
return !first.Equals(second);
}
///
///
/// Complex
/// Complex
public static Complex operator+(Complex first, Complex second)
{
return new Complex(first.m_real + second.m_real,
first.m_imag + second.m_imag);
}
///
///
/// Complex
/// Complex
public static Complex operator-(Complex first, Complex second)
{
return new Complex(first.m_real – second.m_real,
first.m_imag – second.m_imag);
}
///
///
/// Complex
public static Complex operator-(Complex first)
{
return new Complex(-first.m_real, -first.m_imag);
}
///
///
/// Complex
/// Complex
public static Complex operator*(Complex first, Complex second)
{
return new Complex((first.m_real * second.m_real) –
(first.m_imag * second.m_imag),
(first.m_real * second.m_imag) +
(first.m_imag * second.m_real));
}
///
///
/// Complex
/// double
public static Complex operator*(Complex first, double second)
{
return new Complex(first.m_real * second, first.m_imag * second);
}
///
///
/// Complex
/// Complex
public static Complex operator/(Complex first, Complex second)
{
//return (first * second.Conjugate()) /
// ((second.m_real * second.m_real) +
// (second.m_imag * second.m_imag));
double scalar;
double ratio;
if (Math.Abs(second.m_real) >= Math.Abs(second.m_imag))
{
ratio = second.m_imag / second.m_real;
scalar = 1d / (second.m_real + (second.m_imag * ratio));
return new Complex(scalar * (first.m_real + (first.m_imag*ratio)),
scalar * (first.m_imag – (first.m_real*ratio)));
}
else
{
ratio = second.m_real / second.m_imag;
scalar = 1d / ((second.m_real * ratio) + second.m_imag);
return new Complex(scalar * (first.m_real*ratio + first.m_imag),
scalar * (first.m_imag*ratio – first.m_real));
}
}
///
///
/// Complex
/// double
public static Complex operator/(Complex first, double second)
{
return new Complex(first.m_real / second, first.m_imag / second);
}
///
///
/// Real part
public static implicit operator Complex(double real)
{
return new Complex(real);
}
///
///
public static Complex i
{
get { return new Complex(0, 1); }
}
///
///
public static double Tolerance
{
get { return s_tolerance; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException
("Tolerance must be greater than 0");
s_tolerance = value;
}
}
}
}
[/csharp]
Complex number class
//http://extensionlibrary.codeplex.com/ //The MIT License (MIT) using System; using System.Collections.Generic; using System.Text; namespace ExtensionLibrary.Mathematics { /// <summary> /// /// </summary> public class Complex { #region Fields private double imag; private double real; #endregion #region Properties public double Imag { get { return imag; } set { imag = value; } } public double Real { get { return real; } set { real = value; } } #endregion #region Constructors public Complex() { imag = 0.0; real = 0.0; } public Complex(double imag, double real) { this.imag = imag; this.real = real; } #endregion #region Methods public static Complex Add(Complex c1, Complex c2) { return new Complex(c1.imag + c2.imag, c1.real + c2.real); } public static Complex Substract(Complex c1, Complex c2) { return new Complex(c1.imag - c2.imag, c1.real - c2.real); } public static Complex Multiple(Complex c1, Complex c2) { throw new NotImplementedException(); } public static Complex Divide(Complex c1, Complex c2) { throw new NotImplementedException(); } public static Complex Negative(Complex c) { return new Complex(-c.imag, -c.real); } public static Complex Sin(Complex c) { throw new NotImplementedException(); } public static Complex Cos(Complex c) { throw new NotImplementedException(); } public static Complex Tan(Complex c) { throw new NotImplementedException(); } public static Complex Sinh(Complex c) { throw new NotImplementedException(); } public static Complex Cosh(Complex c) { throw new NotImplementedException(); } public static Complex Tanh(Complex c) { throw new NotImplementedException(); } public static Complex Sqrt(Complex c) { throw new NotImplementedException(); } public static Complex Exp(Complex c) { throw new NotImplementedException(); } public static Complex Pow(Complex x, Complex y) { throw new NotImplementedException(); } #endregion public override string ToString() { if (double.IsNaN(real) || double.IsNaN(imag)) { return double.NaN.ToString(); } if (double.IsNegativeInfinity(real) || double.IsNegativeInfinity(imag)) { return double.NegativeInfinity.ToString(); } if (double.IsPositiveInfinity(real) || double.IsPositiveInfinity(imag)) { return double.NegativeInfinity.ToString(); } if (imag == 0.0) { return real.ToString(); } if (real == 0.0) { return imag == 0.0 ? "0" : string.Format("{0}i", imag); } return string.Format("{0} + {1}i", real, imag); } } }
A Complex Number Class
/* A Programmer's Introduction to C# (Second Edition) by Eric Gunnerson Publisher: Apress L.P. ISBN: 1-893115-62-3 */ // 25 - Operator OverloadingA Complex Number Class // copyright 2000 Eric Gunnerson using System; struct Complex { float real; float imaginary; public Complex(float real, float imaginary) { this.real = real; this.imaginary = imaginary; } public float Real { get { return(real); } set { real = value; } } public float Imaginary { get { return(imaginary); } set { imaginary = value; } } public override string ToString() { return(String.Format("({0}, {1}i)", real, imaginary)); } public static bool operator==(Complex c1, Complex c2) { if ((c1.real == c2.real) && (c1.imaginary == c2.imaginary)) return(true); else return(false); } public static bool operator!=(Complex c1, Complex c2) { return(!(c1 == c2)); } public override bool Equals(object o2) { Complex c2 = (Complex) o2; return(this == c2); } public override int GetHashCode() { return(real.GetHashCode() ^ imaginary.GetHashCode()); } public static Complex operator+(Complex c1, Complex c2) { return(new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary)); } public static Complex operator-(Complex c1, Complex c2) { return(new Complex(c1.real - c2.real, c1.imaginary - c2.imaginary)); } // product of two complex numbers public static Complex operator*(Complex c1, Complex c2) { return(new Complex(c1.real * c2.real - c1.imaginary * c2.imaginary, c1.real * c2.imaginary + c2.real * c1.imaginary)); } // quotient of two complex numbers public static Complex operator/(Complex c1, Complex c2) { if ((c2.real == 0.0f) && (c2.imaginary == 0.0f)) throw new DivideByZeroException("Can't divide by zero Complex number"); float newReal = (c1.real * c2.real + c1.imaginary * c2.imaginary) / (c2.real * c2.real + c2.imaginary * c2.imaginary); float newImaginary = (c2.real * c1.imaginary - c1.real * c2.imaginary) / (c2.real * c2.real + c2.imaginary * c2.imaginary); return(new Complex(newReal, newImaginary)); } // non-operator versions for other languages public static Complex Add(Complex c1, Complex c2) { return(c1 + c2); } public static Complex Subtract(Complex c1, Complex c2) { return(c1 - c2); } public static Complex Multiply(Complex c1, Complex c2) { return(c1 * c2); } public static Complex Divide(Complex c1, Complex c2) { return(c1 / c2); } } public class AComplexNumberClass { public static void Main() { Complex c1 = new Complex(3, 1); Complex c2 = new Complex(1, 2); Console.WriteLine("c1 == c2: {0}", c1 == c2); Console.WriteLine("c1 != c2: {0}", c1 != c2); Console.WriteLine("c1 + c2 = {0}", c1 + c2); Console.WriteLine("c1 - c2 = {0}", c1 - c2); Console.WriteLine("c1 * c2 = {0}", c1 * c2); Console.WriteLine("c1 / c2 = {0}", c1 / c2); } }
Demonstates using checked keyword to detect an overflow 2
/* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794 */ // // OvrFlow1.cs -- Demonstates using checked keyword to detect an overflow. // // Compile this program with the following command line: // C:>csc OvrFlow1.cs // namespace nsOverflow { using System; public class OvrFlow1 { static public void Main () { int large = 2147483647; int larger = large; try { larger = checked (++larger); } catch (OverflowException e) { Console.WriteLine ("The operation caused an overflow"); Console.WriteLine (e.Message); } Console.WriteLine ("large = " + large); Console.WriteLine ("larger = " + larger); } } }