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 official coach outlet online on 16 de janeiro de 2017 - 12:31 pm

    Thank you pertaining to spreading that wonderful content on your internet site. I noticed it on the internet. I may check back again whenever you publish additional aricles.
    official coach outlet online

  2. #2 by http://autoinsurancequotesem.us/OK/Oklahoma-City/non-owners-auto-insurance-quotes/ on 16 de janeiro de 2017 - 12:42 pm

    Impatient de voir le programme et les intervenants. Go SEOcamp ! Go !Note, pour mémoire je rappelle que la soirée en fin de 1ère journée avait été très appréciée par les participants !

  3. #3 by louis vuitton bag outlet on 16 de janeiro de 2017 - 1:07 pm

    Fascinating information! I cant believe Ive finally found the information Ive been searching for for so long. Thank you!
    louis vuitton bag outlet http://www.long-beach-air-conditioning.com/louis-vuitton/

  4. #4 by jordan 12 for sale on 16 de janeiro de 2017 - 1:21 pm

  5. #5 by north face outlet pa on 16 de janeiro de 2017 - 1:34 pm

    Hi there, just became alert to your blog through Google, and found that it is truly informative. I am gonna watch out for brussels. I’ll appreciate if you continue this in future. Many people will be benefited from your writing. Cheers!
    north face outlet pa http://www.easyinboxmailer.com/north-face/

  6. #6 by http://www.carinsuranceratescto.info/ on 16 de janeiro de 2017 - 1:57 pm

    Dear Everone my name is Lily and I am 11 years old. I go to Spratton C.E Primary School. Our closest town is Northampton about 6 miles away. My fvaiurote things are football and swimming. I play for West Haddon Foxes. Our coach was a student teacher in our class last year.Next September I will be going to Guilsborough Secondary School which will be different to here as we have only 56 students and they have 1400! I have a rabbit called Ben.

  7. #7 by homeowners insurance florida geico on 16 de janeiro de 2017 - 3:20 pm

    There is visibly a lot to realize about this. I think you made various nice points in features also.

  8. #8 by christian louboutin outlet usa on 16 de janeiro de 2017 - 4:14 pm

    shelagh scandal eklund stromboli jacomet cavern garnett hildebrandt waylay
    christian louboutin outlet usa http://www.christianlouboutinoutlet.online

  9. #9 by patagonia outlet dillon on 16 de janeiro de 2017 - 4:41 pm

    Whilst I have to disagree on a few of the info, however I still truly liked it. I look forward to looking at far more of your posts.
    patagonia outlet dillon http://www.patagoniaoutlet.us

  10. #10 by car insurance quotes online compare on 16 de janeiro de 2017 - 5:49 pm

    What really is a blog page and how should i start one?

  11. #11 by gedpeu on 16 de janeiro de 2017 - 6:00 pm

    アルパカ混で厚手のニットですので、防寒性抜群です!ボタンの閉め方によっても印象が変わってスタイリング幅の出せる1枚です。 どれもかわいいデザインのものばかりです☆☆この靴は「これぞ、イタリア!」っていう雰囲気!!イタリアのモカシン業界を牽引するメーカー、STOKTON(ストックトン)。 [url=http://martinjun.cz/wp-content/special/moncler_1/index.html]モンクレール レディース[/url]
    ソウル市は偽ブランド品の販売にかかわっていた容疑者65人を検挙したという。 荷物を一度ホテルへ置きに帰って、すぐに広蔵市場へ高麗人参茶を買いに行きました。
    [url=http://collegelifenetherlands.nl/montp/moncler_1/index.html]モンクレール ブランド[/url] お電話でのご注文の場合、代金引換のみ、送料はお客様負担となります。 モンクレール ヴィンテージダウン 11-3サイズ 山登りをする方、今時期でも着れますよ。
    [url=http://apievaikus.eu/souka/moncler_1/index.html]モンクレール ダウン ウール[/url]
    ひらいしやクリーニングHP(ひらいしやには、72年間の蓄積されたしみ抜き技術があります!!)毎日5点以上のシミ処理をこの72年間続けてきた実績があります。 光青デニム ジャケット通り風 t シャツをマッチングし春コートと黒ハイウエスト ショート パンツ、リミックス、非常に背が高く、階層化薄さ、幾何学的段タイツ、黒革のブーツ、パンクのような風の味。 [url=http://fglpowerproducer.com/islain/moncler_1/index.html]モンクレール サンダル[/url]
    バイカージーンズは、おNEW!(^-^)チョット、、、スリム過ぎたかな?(笑)頑張ろう!ちょいワルおやじ!最近、お洒落に少しうとくなってきた感じ…年とともに感度が鈍ってくる。 お勧めじゃないです 笑 本日は、最近入荷しましたDIESELの商品ご紹介ですショルダーやポケットにデニムをプラスしたカジュアルなジップブルゾン。
    [url=http://ibbotechnologies.com.br/lucie/moncler_1/index.html]モンクレール セレクト ショップ[/url] 買い付けのリクエストもお受け出来ますので、このモデルのこの色、このサイズ、購入予算といった具合にお問い合わせ頂いたら、買い付ける事も可能です。 当方注:この時期に報告に来ると言う事は、「汚染実態」が厳しいためであろう。
    [url=http://collegelifenetherlands.nl/montp/moncler_1/index.html]モンクレール ダウン 店舗[/url]

  12. #12 by http://besteronlinekredit.pw/7000-euro-kredit-hausfrau-records.html on 16 de janeiro de 2017 - 7:08 pm

    the financing will be actively invited the community and businesses to participate, the current state is no consideration of levying these two taxes. ‘s drinking water standards,air jordan, the basic line with international standards At said Qi Yang,air jordan pas cher, to secure the water functional area water quality attainment rate of 80% in 2015 to 2030 water quality basic standards. Related articles: weird emphasis on creative games to attract a large number of playing Luntai is located in the Tianshan Mountains “School’s negligence has caused candidates retention. Unreasonable it

  13. #13 by north face store locator on 16 de janeiro de 2017 - 7:15 pm

    After all, what a nice web site and informative posts, I will add backlink bookmark this web site?
    north face store locator

  14. #14 by louis vuitton outlet sale on 16 de janeiro de 2017 - 7:43 pm

    Very nice site you have here, has useful information that can apply to anyone :)
    louis vuitton outlet sale

  15. #15 by car insurance quotes online compare on 16 de janeiro de 2017 - 7:48 pm

    We post them, they obtain 1 or 2 views, and then no more. I would like my content to do more than just give us a few sights… how do I have them on the search engines or something similar to that? Will no one ever go to my blog just because I actually don’t post every day?.

  16. #16 by compare insurance company RATINGs on 16 de janeiro de 2017 - 7:52 pm

    Definitely believe that which you stated. Your favorite reason appeared to be on the net the easiest thing to be aware of. I say to you, I certainly get annoyed while people consider worries that they plainly do not know about. You managed to hit the nail upon the top and also defined out the whole thing without having side effect , people can take a signal. Will probably be back to get more. Thanks

  17. #17 by http://besteronlinekredit.pw/vordruck-kreditvertrag-download-kostenlos-word.html on 16 de janeiro de 2017 - 8:55 pm

    Please let me know if you’re looking for a article writer for your weblog. You have some really good articles and I believe I would be a good asset. If you ever want to take some of the load off, I’d absolutely love to write some material for your blog in exchange for a link back to mine. Please shoot me an e-mail if interested. Regards!

  18. #18 by adidas outlet online store usa on 16 de janeiro de 2017 - 10:16 pm

    What I wouldnt give to have a debate with you about this. You just say so many things that arrive from nowhere that Im fairly sure Id have a fair shot. Your weblog is terrific visually, I mean people wont be bored. But others who can see past the videos and the layout wont be so impressed with your generic understanding of this topic.
    adidas outlet online store usa

  19. #19 by patagonia student discount on 16 de janeiro de 2017 - 10:44 pm

    Regarded as a buy the sony the search engines tv box?I am specialist buying one today pertaining to downstairs. It is the sony one considering the built in blu ray(need a new blu ray downstairs at any rate.
    patagonia student discount

  20. #20 by http://onlinekrediteimvergleich.top/kredit-bei-der-bank-als-azubi.html on 16 de janeiro de 2017 - 10:47 pm

    Here’s another “Shorter Christoher Hitchens” from another one of his previous “War Rulez!” articles:No matter how bad things actually get in Iraq, I can conjure up far, far more terrible things from my imagination, therefore invasion/occupation was the right thing to do.

  21. #21 by kredit privat ev schlecht prüfung on 16 de janeiro de 2017 - 11:15 pm

    Thank God! Someone with brains speaks!

  22. #22 by kreditvermittlung zander youtube on 16 de janeiro de 2017 - 11:29 pm

    Wanted to drop a remark and let you know your Feed is not working today. I tried including it to my Google reader account but got absolutely nothing.

  23. #23 by coreyme on 16 de janeiro de 2017 - 11:49 pm

    Microsoftの70-347日本語認定試験を除いて、最近非常に人気がある試験はまたMicrosoft、Cisco、IBM、SAPなどの様々な認定試験があります。 ちよちゃんと同じ「メーカーサポートなど不要」と思っているようなユーザーならともかく、初心者の人に「近いうちにまた撤退するかもしれない、聞いたこともないだろう」なブランドはお勧めしにくいですね。 [url=http://fmcorner.com/forum/viewtopic.php?f=5&t=697857&sid=dcb97fd5be220d32049b5c63bcbc3e35]produkey windows 10[/url]
    マイクロソフトアカウントを要求されるので、現在使っているMSNのhotmailアドレスとPWを入力します。 70-346(Office 365 の ID と要件の管理)試験の対象者はIT プロフェッショナルです。
    [url=http://foropincha.informe.com/posting.php]office2016 プロダクト キー[/url]  Windowsタブレット向けバージョンのOfficeアプリの見た目と操作性も同じになるとされている。  このkeyhole社は、2004年にGoogleに買収。
    [url=http://creationvsevolution.freeforums.org/win8-1-t42986.html]windows 7 ソフト[/url]
    明日の天気予報わ雨で、雨でも工事遣るんぢゃろうか?・・・。 営業部はセールスリードを追跡するために Microsoft Office ドキュメ ントを使用しています。 [url=http://lea-aix.leforum.eu/t115629-microsoft-office-personal-2010.htm#p129403]produkey windows 10[/url]
    *辻堂駅近くには大マーケットが誕生して、今後が楽しみな駅ですが駅舎もレトロ調に新装すれば凄いと思います。 若干、RAWの現像などが、遅い気がしますが、PHOTOSHOPがきちんと動くので、これしかありません。
    [url=http://gamersconnect.net/forum/viewtopic.php?f=4&t=66024]windows8 セットアップ[/url] ところがこれ、Windows10では(確認してませんが恐らくWindows8でも)エラーが出てインストールできません。 新しい会社の方針は 90 日後に削除済みゕ゗ テムフォルダにのみ電子メールメッセージを削除する保持ポリシーを持っているいくつかの既存のメールボックスを必要とします。
    [url=http://fmcorner.com/forum/viewtopic.php?f=5&t=697857&sid=dcb97fd5be220d32049b5c63bcbc3e35]windows8 セットアップ[/url]

  24. #24 by Chandra on 17 de janeiro de 2017 - 12:00 am

    The info talked about in the report are a number of the best out there

  25. #25 by android games for pc download on 17 de janeiro de 2017 - 12:01 am

    Some truly great info , Gladiolus I found this.

  26. #26 by muster kredit vorzeitig ablösen on 17 de janeiro de 2017 - 12:18 am

    that his points are fair without anything to back it up. “there’s probably no way i can change ur opinion” yet u couldnt say a single valid reason other than insulting me?? and that made me a idiot? real mature.

  27. #27 by http://besterkreditvergleich.net/sofortkredit-hausfrau-wiki.html on 17 de janeiro de 2017 - 12:18 am

    The President knows that the Congress is too lazy and self focused to do anything about his violations of the Constitution. They won't even deal with the debt and taxation problem that is causing such chaos. We must get term limits to make it easier to replace MC's who do not represent their constituents.

  28. #28 by gucci outlet store online on 17 de janeiro de 2017 - 12:42 am

    Dont be fooled by.
    gucci outlet store online

  29. #29 by The Best Vibrator on 17 de janeiro de 2017 - 12:49 am

    always a massive fan of linking to bloggers that I enjoy but really don’t get lots of link adore from

  30. #30 by coach diaper bag outlet store online on 17 de janeiro de 2017 - 1:46 am

    that that way Im sure there will be hundreds of people that appreciate this information. Im sure all of us readers appreciate your efforts as much as me!
    coach diaper bag outlet store online

  31. #31 by Summayls on 17 de janeiro de 2017 - 2:25 am

    一度ダメだったものが、適合しているというのは何とも不思議です。 前のエントリ/msoffice_crossing/36359363.htmlでご紹介した、MOS 2013試験の更新(2015/2/4)に対応したMOSテキスト『MOS攻略問題集 Word 2013[第2版]』は4月1日に取次搬入の予定です。 [url=http://www.office-noguchi.jp/modules/d3forum/index.php?post_id=9609]produkey office 2013[/url]
    それでも2着とはクビ差も3着とは5馬身開いており、上がり3ハロン34秒2と思った以上に切れる脚も披露。  ブラザーが燃料電池システムの開発において1つの目標としたのが、「72時間以上」の連続運転性能だという。
    [url=http://b2bforum.vforums.co.uk/board/BQ1/topic/1918/action/view_topic/office-2013]windows 8.1 ソフト[/url] ただ、この陰には大変多くのコントリビューターなどのボランティアの方々や企業の無償供与があってこそだと思います。 Pass4Test のMicrosoftの70-346日本語問題集を利用することをお勧めいたします。
    [url=http://belafadiga.forumfree.org/index.php?&act=ST&f=15&t=11164]office2013 の プロダクト キー[/url]
    そして、我々自身も『自然の一部』であり、決して『人間は特別な存在』ではないのです。 それはより良く自分自身を向上させることができますから。 [url=http://pspmovieking.forumcity.com/viewtopic.php?p=1001#1001]office 2016 価格[/url]
    答えるために、 正しいターゲットに適切な??コ ードセグメントをドラッグしてください。  そのため、独立性、即決性、規律維持という、軍事裁判に固有の必要性に応ずることができず、軍の自己完結的な組織的行動と規律維持を阻害している。
    [url=http://namazu.twiple.jp/forum/viewtopic.php?pid=119388#p119388]microsoft office 安い[/url] アメリカのMicrosoft本社から現金ではない形で慰謝料が送られてくることになりました。 それに、Precisionは使い勝手が、、、、、、同じプラットフォームのLatitudeよりも動きがいいんだよね。
    [url=http://dendroidrp.com/forum/index.php?topic=1194896.0]windows8 1 ダウンロード[/url]

  32. #32 by louis vuitton buy online on 17 de janeiro de 2017 - 3:43 am

    Good post. I be taught one thing more challenging on completely different blogs everyday. It would always be stimulating to learn content material from different writers and practice a bit one thing from their store. I’d choose to make use of some with the content material on my weblog whether or not you don’t mind. Natually I’ll provide you with a link on your web blog. Thanks for sharing.
    louis vuitton buy online

  33. #33 by yeezy boost 350 on 17 de janeiro de 2017 - 4:31 am

1 242 243 244
(não será publicado)