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 Best Insulated Water Bottle 2017 on 29 de abril de 2017 - 7:24 pm

    I have been checking out some of your posts and i must say pretty clever stuff.
    I will make sure to bookmark your site.

  2. #2 by Best Insulated water Bottle 2017 on 29 de abril de 2017 - 7:38 pm

    Wow! Thank you! I constantly wanted to write on my site something like that.
    Can I take a portion of your post to my site?

  3. #3 by Google on 29 de abril de 2017 - 8:58 pm

    Usually posts some quite fascinating stuff like this. If youre new to this site.

  4. #4 by Google on 29 de abril de 2017 - 10:20 pm

    Just beneath, are numerous totally not related web-sites to ours, however, they’re surely really worth going over.

  5. #5 by Dreama Westray on 29 de abril de 2017 - 10:21 pm

    Amazing blog! Do you’ve got any suggestions for aspiring writers? I’m hoping to start my own weblog soon but I’m a little lost on everything. Would you suggest starting with a totally free platform like WordPress or go for a paid option? You can find so several choices out there that I’m totally overwhelmed .. Any tips? Appreciate it!

  6. #6 by thrusting vibrator on 30 de abril de 2017 - 2:16 am

    Just want to say your article is as surprising. The
    clarity to your put up is simply excellent and i can suppose you’re knowledgeable on this subject.
    Well along with your permission let me to clutch your feed to stay up to date with forthcoming post.
    Thanks 1,000,000 and please continue the rewarding work.

  7. #7 by http://news.saveindex.xyz/saveindexxyz/327.asp on 30 de abril de 2017 - 2:19 am

    I have purchased it brand of bracelet a few days. Every single one is very sweet, established well, cannot tarnish and also significant based on which one particular you buy as well as that your provide that it to.

  8. #8 by rebecca minkoff outlet on 30 de abril de 2017 - 3:34 am

    Howdy, i read your blog often and i own an analogous one and i used to be simply wondering if you get a lot of spam comments? If thus how do you stop it, any plugin or anything youll be able to advise? I get thus much lately its driving me mad so any help is very abundant appreciated. It costs about $10 more on a comparable HP printer, and $75 on a Canon.
    rebecca minkoff outlet http://www.6pmall.store

  9. #9 by purchase viagra on 30 de abril de 2017 - 4:33 am

    Molto probabilmente perchè non tutti conoscono l’HTML… comunque è sempre possibile selezionare e trascinare in un nuovo tab l’URL, che anche se “tagliato” è sempre lì, basta assicurarsi di selezionarlo fino alla fine.A proposito: la pratica feature che permette di selezionare e trascinare un url l’hanno imparata alla microsoft? Sono riusciti ad inserirla in IE7?

  10. #10 by sildenafil on 30 de abril de 2017 - 4:51 am

    Pin my tail and call me a donkey, that really helped.

  11. #11 by viagra online on 30 de abril de 2017 - 6:08 am

    Alright alright alright that’s exactly what I needed!

  12. #12 by Alat pemadam kebakaran on 30 de abril de 2017 - 6:49 am

    I want to get across my admiration for your kind-heartedness in support of men and women that really want help with in this concept. Your special dedication to passing the message throughout has been quite advantageous and has usually allowed somebody like me to attain their endeavors. Your informative instruction signifies so much a person like me and further more to my colleagues. Many thanks; from everyone of us.

  13. #13 by Link alternatif w88 on 30 de abril de 2017 - 7:13 am

    I have already been blogging since last month, my blog was listed already on the internet but throughout the test we conducted, we search for a particular keyword related on my blog but it just shows the blog title and it directs me to the homepage not on the actual post. Helping you!!!.

  14. #15 by cheap Louis Vuitton outlet on 30 de abril de 2017 - 8:46 am

    This is this kind of a fantastic resource that you are offering and you give it away free of charge. I adore seeing internet sites that understand the worth of offering a top quality resource for free. It?s the outdated what goes about arrives about program.
    cheap Louis Vuitton outlet http://www.nordstromoutlet.online

  15. #16 by Louis Vuitton Outlet Online on 30 de abril de 2017 - 9:12 am

    This is a great website, might you be involved in doing an interview regarding just how you designed it? If so e-mail me!
    Louis Vuitton Outlet Online http://www.handbagsoutlet.store

  16. #17 by barbour trousers sale on 30 de abril de 2017 - 9:32 am

    Hello. remarkable job. I did not imagine this. This is a remarkable story. Thanks!
    barbour trousers sale http://www.discountbarbour.online

  17. #18 by dobpee on 30 de abril de 2017 - 9:56 am

    ◇ひさびさに、シールズやチャンシマさんやこたつぬこさんや池田さんのツイッターを紹介しておきます。 MBC水木ドラマ「W」は2016年ソウル、同じ空間の違う次元、現実とバーチャルリアリティを交差して繰り広げられるロマンチックサスペンスメロドラマで、イ・ジョンソク、ハン・ヒョジュらが出演する。 [url=http://kenken.chu.jp/hinde/dvdbox_1/index.html]シンデレラのお姉さん キャスト[/url]
    Wordオンライン、Excelオンライン、PowerPointオンラインは無料なのです。 ※当ブログにご来訪された時の「最新記事」だけ見て立ち去らずに、未読・お見逃し・お見落とし、及び「飛び石閲覧」の無いよう、各更新記事を、キチンと順番にご覧ください。
    [url=http://www.bobsiemonsma.nl/tukan/dvdbox_1/index.html]トッカン 特別国税徴収官 DVD box[/url] 漢字を見て意味を推測して読まずに飛ばし読みしていた。 最近の車はラジオのアンテナがショートタイプでブースター電源が必要になるのでリモートの青いケーブルも接続しないとAMラジオが聴けなくなるので注意してください。
    [url=http://action-group.be/seikin/dvdbox_1/index.html]トキメキ 成 均 館[/url]
    この日はバレンタインデーということもありささやかながらチョコを用意して行きましたよん♪О課長と、店長と工場長にプレゼントしましたそしたらすごく喜んでくれて持って行って良かった~って思いましたさてさて、ルークスくんですがこんな感じです。 しかし、これに対して、独裁政権は、「アメ=ばらまき」と「ムチ=軍や秘密警察による監視や弾圧」を使い分けることで巧みに権力を維持し続けた。 [url=http://illuminatum.eu/arden/dvdbox_1/index.html]シティー ハンター[/url]
    それに対してHFAS1は、広義に考えればLinux OSを積んだコンピューターなのだが、徹底した音質の吟味と対策が行われ、シャーシ、回路設計、使用パーツ、その全てが音質向上だけのために投入されている。 片岡 沙耶(かたおか さや、1993年7月18日 – )は、日本のタレント、グラビアアイドルである。
    [url=http://www.fikirdil.com/wp-content/golden/dvdbox_1/index.html]ファン ジョンウム[/url]   ルフィはみんなを抱えてひょいっと象から飛び降りましたが、着水はどうするつもりなのでしょうか??(笑)  まぁ、ルフィがいれば、何とでもなりますね。 3.米国でも米戦争屋の正体を暴いているのは主にネットジャーナル 米戦争屋は、ブッシュ米戦争屋ネオコン政権の頃から、米マスコミ統制を強化していますが、それでも、米ネット言論の完全統制には成功していません。
    [url=http://www.bobsiemonsma.nl/tukan/dvdbox_1/index.html]特別国税徴収官[/url]

  18. #19 by sildenafil on 30 de abril de 2017 - 12:09 pm

    If I didn’t love KK I would have responded by suggesting that she could do much better if she used the converter. I would never do that to KK. No matter how mean she is to me all the time and how sometimes she makes me cry . .

  19. #20 by http://news.shoesonlinebuy.xyz/shoesonlinebuyxyz/324.asp on 30 de abril de 2017 - 12:41 pm

    That product or service ended up being in that ideal price I did not believed that the excellence would be and so excellent. It’s striking. This particular mom might adore this concerning Christmas time early morning once she starts gift therefore appears like I spent significantly more, still prices had been just ideal!!

  20. #21 by http://news.haveinc.xyz/haveincxyz/342.asp on 30 de abril de 2017 - 12:42 pm

    This product was at such a very good amount I did not thought the high quality is and so exceptional. It is stunning. The mother will love that regarding Xmas morning once she starts present and it appears as though I devoted alot more, however cost ended up being just great!!

  21. #22 by http://news.hermesreplica.win/hermesreplicawin/440.asp on 30 de abril de 2017 - 12:42 pm

    I have bought your brand concerning bracelet a number of period. Every single a person is very sweet, prepared very well, cannot tarnish and/or meaningful based on what an you purchase and/or whom we provide this in order to.

  22. #23 by http://news.cheapmoncler.win/cheapmonclerwin/417.asp on 30 de abril de 2017 - 12:43 pm

    This particular device ended up being in that ideal price tag I never ever considered the excellence is hence exceptional. Its breathtaking. The mom is going to prefer it on Christmas time day when she starts gifts therefore seems like I spent significantly more, and yet cost is just great!!

  23. #24 by http://news.portside.xyz/portsidexyz/313.asp on 30 de abril de 2017 - 2:08 pm

    I’ve purchased your brand of bracelet a few occasions. Every single one is extremely sweet, has made very well, does not tarnish furthermore important depending on what a person you buy additionally whom shoppers present information technology to.

  24. #25 by http://news.cartierbraceletsreplica.pw/cartierbraceletsreplicapw/415.asp on 30 de abril de 2017 - 2:08 pm

    Your product is in such a very good price I did not idea that high quality is so exceptional. It is pretty. That mother will likely really like that it regarding Holiday morning where she opens up gift therefore seems like I devoted much more, although rates had been only ideal!!

  25. #26 by cheap viagra on 30 de abril de 2017 - 2:28 pm

    வாà®´்த்துகள் à®·ாà®®ா…குழந்தைக்கு என்னுடைய அன்பு…உடம்பினை பாà®°்த்து கொள்ளுà®™்க…

  26. #27 by viagra online on 30 de abril de 2017 - 3:29 pm

    Eu fiz minha inscrição , mas no dia não consegui imprimir meu comprovante , agora que as incrições já foram encerradas como eu faõ pra imprimir a 2 via do comprovante ?

  27. #28 by Link altenatif ibosport on 30 de abril de 2017 - 4:03 pm

    I just uncovered using Joomla for powerful website design but feel the limitation upon use of themes is a major minus. I think it should be feasible to make use of my own design template in the style. Anyone help?.

  28. #29 by sildenafil on 30 de abril de 2017 - 4:48 pm

    dunno who that is, pirates 2, rock, brad paisley, carrie underwood, american idol, colorado, michigan state i guess, princeton, brother, dunno what that is, KELLY CLARKSON, dunno who that is, ice skating, Puppym embarassing dance, Singing Bee becuz its not a rip off, grease, christmas, uh dunno, stunt person, dunno what that is, diamonds, michigan i guess, COMPUTER, ENGLISH!phew!

  29. #30 by dating tips on 30 de abril de 2017 - 4:58 pm

    always a massive fan of linking to bloggers that I adore but do not get a lot of link appreciate from

  30. #31 by http://news.vancleefreplica.top/vancleefreplicatop/333.asp on 30 de abril de 2017 - 7:22 pm

    This one goods was at such a great price tag I never considered your grade is so that exceptional. Its striking. It mother will love that it in Christmas time day when she starts gift therefore appearance like I invested much more, and yet rates was exclusively great!!

  31. #32 by http://news.ordersoho.com/ordersoho/1024.asp on 30 de abril de 2017 - 7:22 pm

    It supplement is in that very good pricing I never ever attention ones top quality would be hence exceptional. Its gorgeous. The mama might love information technology concerning Christmas time morning when she starts gift therefore appears as though I devoted significantly more, still pricing had been exclusively awesome!!

  32. #33 by www.krogerfeedback.com on 30 de abril de 2017 - 7:44 pm

    Do you mind if I quote a few of your posts as long as I provide credit
    and sources back to your webpage? My blog site is in the exact same area of interest as yours and my users would genuinely benefit from a lot of the information you provide here.
    Please let me know if this ok with you. Cheers!

  33. #34 by coreuhf on 30 de abril de 2017 - 8:36 pm

    ユーザーフォーム内に直接プログラミングをしていくので、標準モジュールへの記述だけ勉強してきた僕には、非常にためになります。 Sarahのポリスレコードを見る限り 一年に一回は何らかのトラブルを起こしているから 今回の仮保釈も長く持たないと踏んでいます。 [url=http://www.keygoodjp.com/windows-10-education-86.html]produkey windows 10[/url]
    C. データ損失防止ポ リシーを作成します。 これからも、コンペ等楽しいイベント企画していきますので、ぜひ、お気軽にご参加ください!!それではこのへんでトコろんでした。
    [url=http://www.keygoodjp.com/acrobat-x-11.html]Acrobat 11 認証[/url] HDDとSSDを入れ替えて、Windows7インストールして、プロダクトIDをPC底面の番号に変更し、Windows10へ無事アップグレードを完了しました。 複数にまたがる、ハードデスクの整理も、これからの課題です。
    [url=http://www.keygoodjp.com/office-home-and-business-2016.html]office2016 personal 価格[/url]
      思えば、ここでPWか52度でしっかり出すべきだったか。 しょぼいというか、なんというか、、、ただ、4連続パーは本当に何年振り?と聞きたいくらいの久しぶり。 [url=http://www.keygoodjp.com/windows-10.html]windows 10 の インストール[/url]
    もしそういう説明をしたとすればそれは重大なミスであり、それを買ったユーザーから契約を破棄すると言われてもしかたがないことだ、と言った。 あるいは、無料で試験70-347日本語問題集を更新してあげるのを選択することもできます。
    [url=http://www.keygoodjp.com/microsoft-office-professional-2013-plus32.html]office2013 の プロダクト キー[/url] プロの写真家だけでなく、総額で100万円規模のカメラやレンズを持ち、写真を趣味とするハイアマチュア層もターゲットのひとつ。 組織は SharePointOnline と使用するための第 2 のドメ゗ン名を購入します。
    [url=http://www.keygoodjp.com/microsoft-office-project-professional.html]office2013 ソフト[/url]

  34. #35 by emogejni on 30 de abril de 2017 - 8:37 pm

    1999年に高島礼子と結婚し、2015年に高島の父の介護に専念するため芸能界を引退した高知だが、その交友関係には“不穏な影”がちらついていた。 最大25kΩの単純負荷(ポテンショメータ)を持つエクスプレッションで動作します。 [url=http://www.minkita.net/modules/d3forum/index.php?post_id=2085]office2016 プロダクト キー[/url]
    今日は眠たい眼をこすりつつベッドから身を起こし、眩いばかりの太陽はオーバーだけど、意外に予報が外れたのか好天気です。  情報が出回る前からアドオン処理に時間がかかり、一々許可の有無を求められるのに苛々していたこともあり、別ブラウザを探しました。
    [url=http://izunotabi.jp/modules/wordpress/index.php?p=1249]office2013 personal 価格[/url] Microsoftの認定試験はIT領域における非常に大切な試験です。 原燃料安を背景とした交易条件の改善などで利益率が改善した。
    [url=http://creationvsevolution.freeforums.org/windows-t50718.html]office2010 メディア 購入[/url]
    しかし見慣れたサインカーブではないことに新鮮な驚きを感じました。 これを「7」または「8」に設定しておいてそれからIEのフォント拡大。 [url=http://hewarwatani.gov.sd/forum/showthread.php?807398-%e3%81%99%e3%81%a7%e3%81%ab%e4%bb%a3%e8%a1%a8%e3%81%ab%e5%86%85%e5%ae%9a%e3%81%97%e3%81%a6%e3%81%84%e3%82%8b%e5%86%85%e6%9d%91%e8%88%aa%e5%b9%b3&p=1355815#post1355815]office2010 personal 価格[/url]
    まぁ承認しなければXPよろしく使えなくなってしまうから拒否する方法などないのだが。 http://www.sankei.com/wired/news/160621/wir1606210001-n1.html>「アストロターフィング」という言葉はもともと、米国で販売されていた人工芝の商品名「アストロターフ」に由来する造語で、「ニセの草の根運動」という意味をもつ。
    [url=http://natsu-oz.versus.jp/xoops/modules/d3forum/index.php?post_id=7205]windows 7 ソフト[/url] ホルンは「紫いも」のがおいしかったなぁ・・・8本入り。  それはネガティブに言えば「イノベーションのジレンマ」であるし、ポジティブな表現で言えば「王道」の手法だ。
    [url=http://mixzing.freeforums.org/windows10-t96407.html]office2016 ソフト[/url]

  35. #36 by www.krogerfeedback.com on 30 de abril de 2017 - 8:40 pm

    Hurrah, that’s what I was seeking for, what a material!
    existing here at this blog, thanks admin of this website.

  36. #37 by Kinky Bondage toys on 30 de abril de 2017 - 8:59 pm

    that is the end of this write-up. Here you will discover some web sites that we consider you will appreciate, just click the hyperlinks over

  37. #38 by Alat pemadam api on 30 de abril de 2017 - 9:22 pm

    I consider something really special in this website .

  38. #39 by how to deal with std on 30 de abril de 2017 - 9:26 pm

    Wonderful story, reckoned we could combine a handful of unrelated information, nevertheless actually really worth taking a look, whoa did one particular understand about Mid East has got much more problerms too

  39. #40 by mont blanc outlet store on 30 de abril de 2017 - 10:51 pm

    Is not marriage an open question, when it is alleged, from the beginning of the world, that such who are in the institution wish to get out and such as are out wish to get in.
    mont blanc outlet store

  40. #41 by http://makis.nu/tak/sara/341.html on 30 de abril de 2017 - 11:03 pm

    Your headset is as stunning because in the picture. This appeared quickly. I’d encourage getting a towel through each and every level while you click things out w / one vapor iron. It doesn’t vapor out with only a steamer. All iron is important. It can be fine, when you cannot trust yourself because of the towel and vapor iron, next choose it up to a professional. Awesome appear.

  41. #42 by http://www.deshvani.in/client/4.html on 30 de abril de 2017 - 11:03 pm

    Your headset had been as spectacular since within the image. This arrived immediately. I’d recommend using a towel more than each level while you push that it over w / letter steam iron. It does not vapor away with merely a steamer. Ones iron had been appropriate. It is very sensitive, when you do not trust yourself aided by the towel plus vapor iron, after that choose they up to a expert. Stunning appear.

1 343 344 345
(não será publicado)