Battle Simulation With Lanchester Model in C#


This post will show a simple implementation of the famous Lanchester equations to simulate battles “evolution”.

For those that does not know this model, i really recomend this and this PDFs. (especially the first one). For the rest of the post, iam assuming that the reader “WILL read” these recomended texts =P.

Lanchester modeling is pretty beautiful cause it is based in very simple hypothesis and even so, it stills very usefull. (not so good as some stochastic models but good enough for lots of situations ).

In simple ways, we have a system of Differential equations to solve. There are LOOOTS of numeric methods avaliable, i choose one that for me is very intuitive and easy to implement. (using EigenValues and Eigen Vectors -> it is graphically intuitive =P)

The following code shows the Lanchester Model Implementation:
I used plain C# with .net and the alglib for math.
Actually, the alglib was used just to get the eigenvalues and eigenvectors of the lanchester diferential system. It could be easily done by “hand”. (calculate roots of the characteristic equation to find the eigenvalues and then substitute in the formal eigenvector/eigenvalue definition equation to get the eigenvectors =P).

The Squad Class (represents one Army =P)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Settlers.Battle
{
    class Squad
    {
        public float numericalStrenght;
        public float effectiveness;
    }
}

The simulator class:

There are some static methods that can be used to discover the winner before the “Battle begin =P” (without explicitelly using the time variable. See the recomended papers to know the reason why we can do this)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Settlers.Battle
{
    class LanchesterSimulation
    {
        public LanchesterSimulation(Squad a1, Squad a2)
        {
            double[,] vects = new double[2,2];
            vects[0, 1] = -a2.effectiveness;
            vects[1, 0] = -a1.effectiveness;
            double[] real = new double[2];
            double[] ima = new double[2];
            double[,] left = new double[2, 2];
            double[,] right= new double[2, 2];

            alglib.rmatrixevd(vects, 2, 2, out real, out ima, out right, out left);

            ev1 = real[0];
            ev2 = real[1];

            auv1x = right[1, 0];
            auv1y = right[0, 0];

            auv2x = right[1, 1];
            auv2y = right[0, 1];

            c2 = (a2.numericalStrenght - (a1.numericalStrenght * auv1y) / auv1x ) * auv1x / (-auv2x * auv1y + auv2y * auv1x);
            c1 = (a1.numericalStrenght - auv2x * c2) / auv1x;

        }

        double ev1, ev2;
        double c2, c1;
        double auv1x,auv1y,auv2x,auv2y ;

        public float GetArmy1Size(float t)
        {
            double resp = c1 * auv1x * Math.Exp(ev1 * t) + c2 * auv2x * Math.Exp(ev2 * t);
            return (float)resp;
        }

        public float GetArmy2Size(float t)
        {
            double resp = c1 * auv1y * Math.Exp(ev1 * t) + c2 * auv2y * Math.Exp(ev2 * t);
            return (float)resp;
        }

        public static Squad WhoWillWin(Squad a1, Squad a2)
        {
            float val = a1.effectiveness * a1.numericalStrenght * a1.numericalStrenght - a2.effectiveness * a2.numericalStrenght * a2.numericalStrenght;
            return val > 0 ? a1 : a2;
        }

        public static Squad[] WhoWillWin(Squad[] a1, Squad[] a2)
        {
            float apower = 0;
            float atotal = 0;
            for (int i = 0; i < a1.Count(); i++)
            {
                apower += a1[i].effectiveness * a1[i].numericalStrenght;
                atotal += a1[i].numericalStrenght;
            }

            float bpower = 0;
            float btotal = 0;
            for (int i = 0; i < a2.Count(); i++)
            {
                bpower += a2[i].effectiveness * a2[i].numericalStrenght;
                btotal += a2[i].numericalStrenght;
            }

            float val = apower * atotal - bpower * btotal;
            return val > 0 ? a1 : a2;
        }
    }

}

That is all for today =P

  1. #1 by Asia tourism on 27 de junho de 2017 - 4:18 pm

    As a Newbie, I am always searching online for articles that can benefit me. Thank you

  2. #2 by feraripoker on 27 de junho de 2017 - 6:42 pm

    amazing concerns totally, you merely obtained a new reader. What can Battle Simulation With Lanchester Model in C# | Ploobs you suggest regarding your publish that you designed a couple of days ago? Any certain?. feraripoker http://www.feraripoker.org/

  3. #3 by http://www.technocoins.win/clash-of-clans-gem-hack-for-android-apk.html on 27 de junho de 2017 - 7:28 pm

    If you’re taking suggestions, I would like to own a Michael Ruhlman special tome on stock making. I know you cover this in your other books, but I think a more exhaustive account of stock making would be seriously appreciated.Now I’m going away to order Walk on Water.

  4. #4 by http://www.usehackgenerator.win/my-little-pony-game-gems-hack.html on 27 de junho de 2017 - 7:40 pm

    I loved Jem! I had Jem, Rio, and Clash dolls. Clash had the best outfit, a glittery teal dress, a neon yellow, cropped fur coat, and her heels were either hot pink or metallic purple. I can’t remember whose shoes belonged to whom.Amber recently posted …

  5. #5 by ecemergency.info on 27 de junho de 2017 - 8:23 pm

    Way cool! Some very valid points! I appreciate you writing this article plus
    the rest of the website is really good.

  6. #6 by self catering accommodation in Nairobi on 27 de junho de 2017 - 8:30 pm

    Good write-up, I’m regular visitor of one’s site, maintain up the nice operate, and It is going to be a regular visitor for a long time.

  7. #7 by real sword on 27 de junho de 2017 - 9:23 pm

    This Was bought as a cosplay prop weapon and works amazingly

  8. #8 by Hediui on 27 de junho de 2017 - 9:28 pm

    10 年以上前にゲーム用として、当時 約 50 万円程かけて自作した Main PC ですが、AGP 世代のパーツ構成の為もはや時代遅れとなり、5 年程前には、現在の PCI – Express のパーツ構成で、約 20 万円程かけて Sub 機を自作。 結果として、XPを使い続けている顧客に対しては、直接的な問題がなくても、メンテナンスなどのサービスを打ち切ることになります。 [url=http://softpcjpjp.com/]win 8.1 インストール[/url]
    なんだかタイミングが良すぎる感じもしますよね。  仕方ないからもう一度最初のダウンロードからやり直した。
    [url=http://www.office2016jpjp.net/]win10 アップグレード[/url]   http://catalog.update.microsoft.com/v7/site/search.aspx?q=kb3189866■【連載】 インチキ呼ばわりされる中国の高速鉄道 9 日中合戦のインドネシア 2016/09/13 近年、中国の高速鉄道がなにかと話題になっています。 (*´∀`*)これだけPRしてもMicrosoftさんからは一円も 貰っては居ませんので・・・悪しからず (^O^)。
    [url=http://www.serialkeys.org/]windows server ライセンス[/url]
    Windows10アップグレードを行い、Microsoftのサーバーから「デジタル権利付与のライセンス認証」を発行してもらい、その後ロールアップして元の環境に戻すまでの操作や画面や手順と所要時間が説明されています。 また、アップルはマルチタッチに関する特許を所有しており、Androidでマルチタッチを利用した端末を発売しているメーカーを特許侵害で提訴している。 [url=http://www.serialkeys.org/]windows server 2012[/url]
    XHS1991.COMは最新の1z1-436問題集と高品質の70-432問題と回答を提供します。 ただしWindows 10には、従来の「Internet Explorer(IE)」ブラウザもひっそりと搭載されている。
    [url=http://www.officehb.com/]windows 7 アップグレード[/url] そこで、データベースから必要なものだけを一覧として取り出します。 正確に言うのなら「勝手にWindows10へのアップグレードを予約したことを表示」し、それに対してユーザーが能動的にそのアップグレードスケジュールを変更し、またWindowsUpdateに登録されているWindows10へのアップグレードを潰す。
    [url=http://www.serialkeys.org/]Microsoft windows server[/url]

  9. #9 by vibrating beads on 27 de junho de 2017 - 9:48 pm

    just beneath, are various totally not associated web sites to ours, nonetheless, they are certainly really worth going over

  10. #10 by Business Service on 27 de junho de 2017 - 11:43 pm

    You have noted very interesting points! ps decent web site.

  11. #11 by Education and Training on 27 de junho de 2017 - 11:54 pm

    I like the valuable info you provide in your articles. I will bookmark your blog and check again here frequently. I am quite sure I will learn a lot of new stuff right here! Best of luck for the next!

  12. #12 by Business Service on 27 de junho de 2017 - 11:58 pm

    I just could not depart your web site before suggesting that I actually enjoyed the standard info a person supply in your guests? Is gonna be back frequently to check out new posts

  13. #13 by Pets and Animal on 28 de junho de 2017 - 12:01 am

    Thanks so much for giving everyone an extremely breathtaking chance to read articles and blog posts from this web site. It is usually so great and also packed with a lot of fun for me personally and my office acquaintances to visit the blog not less than 3 times in a week to study the newest items you have. And lastly, I’m also at all times happy considering the surprising information you serve. Certain 1 points in this post are easily the most efficient I have had.

  14. #14 by Clothing and Accessories on 28 de junho de 2017 - 2:26 am

    I got what you mean , appreciate it for putting up.Woh I am delighted to find this website through google. “I would rather be a coward than brave because people hurt you when you are brave.” by E. M. Forster.

  15. #15 by http://www.technocoins.win/free-boom-beach-hack-for-android.html on 28 de junho de 2017 - 4:22 am

    Ellie you’re in great hands with Mike, when the time comes I would also love to join into the conversation. For now you and Mike get to know each other and one of these days when I am in Chicago maybe we can grab a coffee or even some of that “booze” from Columbus you tweeted about earlier today.

  16. #16 by clubc4.es on 28 de junho de 2017 - 4:53 am

    Hello mates, nice article and good urging commented here, I am in fact
    enjoying by these.

  17. #17 by dig this on 28 de junho de 2017 - 6:38 am

    It really is near impossible to encounter well-updated visitors on this matter, and yet you appear like you realize which you’re revealing! Appreciation

  18. #18 by golden goose outlet 2017 on 28 de junho de 2017 - 6:56 am

    di moss.I può andare oltre, ha detto Phoenix. Si tratta di un mero spreco insensato di vita, di spendere come facciamo noi, sempre vagando su e giù, e mai venendo toany casa al calar della notte. La nostra sorella è perso, e non sarà trovato. Sheprobably morti in mare; o, per qualunque riva del toro mayhave bianco la portò, è ormai tanti anni fa, che non ci sarebbe neitherlove né la c golden scarpe onoscenza tra di noi, dovremmo incontrare di nuovo. Mio padre ci hasforbidden di tornare al suo palazzo, così ho mi deve costruire una capanna di rami, e dimorare here.Well, figlio di Phoenix, ha detto Telefassa, con dolore, si sono cresciuti toTANGLEWOOD TALES58be un uomo, e deve fare come golden goose silver giudichi migliore. Ma, da parte mia, io ancora andare inchiesta della mia povera child.And noi tre andremo insieme a voi! gridarono Cadmo e Cilix, andtheir fedele amico Taso.

  19. #19 by http://www.goldgenerator.win/how-to-get-free-money-on-fifa-15-ps3.html on 28 de junho de 2017 - 7:06 am

    Buenos días Rafa,Lo más cínico de todo es que estas victimas inocentes lo consideran ellos “daños colaterales”, tampoco podemos olvidar que debido a los componentes de las armas utilizadas en la primera guerra del golfo siguen muriendo de cáncer mucha gente, y que hay niños que nacen con malformaciones, no se poner enlaces en comentarios pero hay una Web: DU Babies , que es dura, muy dura de mirar…Un beso Rafa.

  20. #20 by Sword Customization Saya on 28 de junho de 2017 - 7:51 am

    This sword is very nice and sharp, it is so sharp that I cut through six cans of tea in the same time! It is worth it and always remember to keep it oiled because it will rust other than that is is a very beautiful piece of art I highly recommend this katana

  21. #21 by www.faytech.us/ on 28 de junho de 2017 - 8:46 am

    It’s actually practically extremely difficult to see well-educated viewers on this area, however you appear like you fully grasp which you’re covering! Cheers

  22. #22 by what the best car insurance for young drivers on 28 de junho de 2017 - 8:49 am

    Hello there! This post couldn’t be written any better! Reading this post reminds me of my old room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thank you for sharing!

1 401 402 403
(não será publicado)